Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
strauberry Avatar asked Dec 09 '11 12:12

strauberry


People also ask

Why are attributes private and methods public?

A private attribute provides you a level of protection from the users of your class, for that attribute. If you use a public attribute, you will need to add in more logic to test for invalid values up front, which can be more work, as well as more computationally expensive.

Are attributes private by default in Java?

By default is not private, is "package only" (no key word for that). All classes in same package see the field.

Why do we write public in Java?

public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final .

What is the purpose of Java attributes?

An attribute is another term for a field. It's typically a public constant or a public variable that can be accessed directly. In this particular case, the array in Java is actually an object and you are accessing the public constant value that represents the length of the array.


1 Answers

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.

like image 64
duffymo Avatar answered Sep 17 '22 13:09

duffymo