How to create immutable class without using final keyword?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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:
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).
Last edited by GabrielNegut; May 7th, 2012 at 08:13 AM.
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.Originally Posted by Oracle