I read that to make a class immutable in Java, we should do the following,
- Do not provide any setters
- Mark all fields as private
- Make the class final
Why is step 3 required? Why should I mark the class final?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you don’t mark the class
final, it might be possible for me to suddenly make your seemingly immutable class actually mutable. For example, consider this code:Now, suppose I do the following:
Notice that in my
Mutablesubclass, I’ve overridden the behavior ofgetValueto read a new, mutable field declared in my subclass. As a result, your class, which initially looks immutable, really isn’t immutable. I can pass thisMutableobject wherever anImmutableobject is expected, which could do Very Bad Things to code assuming the object is truly immutable. Marking the base classfinalprevents this from happening.