Why can attributes in Java be public?

I think it’s possible because every rule has its exception, every best practice can be overridden in certain cases.

For example, I often expose public static final data members as public (e.g., constants). I don’t think it’s harmful.

I’ll point out that this situation is true in other languages besides Java: C++, C#, etc.

Languages need not always protect us from ourselves.

In Oli’s example, what’s the harm if I write it this way?

public class Point {
   public final int x;
   public final int y;

   public Point(int p, int q) {
      this.x = p;
      this.y = q;
   } 
}

It’s immutable and thread safe. The data members might be public, but you can’t hurt them.

Besides, it’s a dirty little secret that “private” isn’t really private in Java. You can always use reflection to get around it.

So relax. It’s not so bad.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)