How to create immutable class without using final keyword?
Printable View
How to create immutable class without using final keyword?
final does not mean the class is immutable, you just can't reassign the variable to another object instance.
Example:
Code Java:final MyObject obj = new MyObject(); // obj = new MyObject(); // you can't reassign it obj.setField(true); // but you can modify it
If you want to create an immutable class, don't make any public mutators (methods which modify the object's fields).
Final means different things in difference contexts See Writing Final Classes and Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)
To quote:
Marking a class as final does not by default mean the class is immutable. Encapsulating fields and not providing setters is a step in the right direction, but depending upon what the fields are, one may also need to have some way to deep copy fields which can potentially be modified by clients when accessed by getters.Quote:
Originally Posted by Oracle