Does this below class is immutable?
class Immutable {
private int x;
Immutable(int value) {
this.x = value;
}
public int getX(){
return x;
}
}
-
Class is not final Since no member is visible to sub class
-
Instance Variable x is not final since there is no setter method.
Is there any possiblity this class will break the contract of Immutable functionality without adding any code in this class?
Joshua Bloch in his “Effective Java” states that “you should either design your classes for extensibility or make them non-extensible”.
If flexibility is your primary concern and you have a strong reason to design your immutable class for inheritance – leave this class non-final.
If security is your concern – make this class final and member field final. Because:
Non-final classes can be extended to create a mutable child classes by overriding getter method.
Java is reflective by design. As Belgther told it’s possible to set the value of member field using reflection. (no matter private or public) A long time ago I used this to integrate my specific debugger with another project.