Skip to content
Advertisement

Why can attributes in Java be public?

As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the only interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement