My query is, can a getter method ever return a wrapper data type? Will it violate the principle of Encapsulation? Why not? Is immutability of classes a part of encapsulation?
public class TestGetter{
private Integer a;
public TestGetter(int _a){
a = _a;
}
public Integer getA(){
return a;
}
}
In Some client code:
TestGetter tg = new TestGetter(5);
Integer corruptX = tg.getA();//This should return the reference
corruptX = null;
So now
a = null?
When i run it i dont see a as null.
This is no different to:
Modifying a reference is not the same as modifying the object being referred to.
To answer your question about encapsulation; yes, it’s ok to return a reference to an
Integermember variable, becauseIntegerinstances are immutable.