I am working on some practice questions for the OCP 8.
One question featured a class with private fields and private getter methods. The correct answer was that this code violates encapsulation because the getter methods should have been public.
public class A {
private String a;
private String getA() { return a; }
}
However, another question featured a class with private fields and no getter methods at all. The correct answer was that this code follows encapsulation principles.
public class A {
private String a;
}
Assuming all data fields are private, shouldn't the order of most encapsulated to least be no getter methods, private getter methods and public getter methods?
I know my question might sound opinion-based, but the exam is not.
Private getter methods do not violate encapsulation. That is just nonsense.
I am not expressing an opinion here. It is a fact that a Java private method can only be called within the class that declares it. That is inside the boundary of encapsulation.
Either you have misread the OCP sample question and answer, or they have made a mistake.
Now it could be that what they were trying to ask was whether the example class was an example of good encapsulation or more generally of good OO design.
UPDATE
Seeing the example code, it is hard to say one way or another. It is too unrealistic to make a judgement. (The code is literally useless, but unless we know what its intended use was, we can't really call this bad design.)
Another answer seems to be arguing that private getters are useless. I disagree. Especially since a getter may do other things apart from simply returning a value. Consider this:
private synchronized void setBalance(int newBalance) {
this.balance = newBalance;
}
private synchronized int getBalance() {
return this.balance;
}
This ensures that the caller will see the current value of the balance field even if it was just updated by another thread. Sure we can do it other ways, but this way is good separation of responsibilities.
And there other that a private getter could legitimately do.