You should always make the fields of a class private
. And provide public
accessor methods, to access those fields..
By doing this, you are achieving a level of encapsulation
that is core to any OO language
..
Also, other benefit of not allowing the access directly is that, you can modify your fields according to your need and security before letting the outer class access it..
In fact, it is generally suggested to access the private fields
through getter methods
even in the same class also.. '
This also helps the modification of your class easy..
Suppose, in future, you want to change the way your fields are accessed (That is you want to do some processing on the fields, before returning it).. Now, if you are accessing the fields directly even in your own class.. You would have to go and change at every place.. But if you used getter
to access the fields, you would just need to modify
your getter
method..
public class A {
private int data;
public int getData() {
// Here apart from just return the `data`, you can perform some
// modification also according to your need..
}
}