I am relatively new to Java OO Programming, and have reviewed the questions similar to this, although they don't seem to answer my question directly.
Basically, I understand that if a data member within a class is declared as private, then it is only accessible from within that same class.
My lecturer always advises that ALL attributes should be declared as private - why is this?
Now I am familiar with using GET methods, and my question is, can a private attribute be accessed outside of it's own class via invoking a PUBLIC 'get' method (which returns the aforementioned attribute) from another class?
For example:
public class Class()
{
private int number = 0;
public Class()
{
}
public int getNumber()
{
return number;
}
}
And then from another class:
public class Class2()
{
Class class = new Class();
public void showNumber()
{
System.out.print(class.getNumber());
}
}
Will the second block of code allow the method in showInt() inside Class2 to actually access the private attribute from Class?
I guess I am really struggling with deciding whether any attribute or method should be declared public or private in general..
Is there any particular rule of thumb that should be followed?
Thank you responders for any assistance.
Kind regards
The key point is that a public
get
method only returns the current value of your private member, without giving access to the member itself. This means that you cannot somehow "get" the member and change its value.