Friday, 9 June 2017

Why would one declare an immutable class final in Java?


If you don't mark the class final, it might be possible for me to suddenly make your seemingly immutable class actually mutable.

Example:
package com.dp;
class Immutable {
     private final int value;

     public Immutable(int value) {
           this.value = value;
     }

     public int getValue() {
           return value;
     }
}

public class Mutable extends Immutable {
     private int realValue;

     public Mutable(int value) {
           super(value);
           realValue = value;
     }

     public int getValue() {
           return realValue;
     }
     public void setValue(int newValue) {
           realValue = newValue;
     }

     public static void main(String[] arg){
           Mutable obj = new Mutable(4);
           /**
            * Object obj is Mutable object which seem like Immutable
            * as it has been caste into the parent class.
            */
           Immutable immObj = (Immutable)obj;

           System.out.println(immObj.getValue());
           /**
            * Changing the state on Mutable class which is
            * referenced by the immutable class.
            */
           obj.setValue(8);

           /**
            * It will print the mutable class value field as immObj  
            * contains the instance of the Mutable class.
            */
           System.out.println(immObj.getValue());
     }
}

Notice, In the Mutable subclass, we've overridden the behavior of getValue to read a new, mutable field declared in my Mutable subclass. As a result, our object, which initially looks immutable, really isn't immutable (contains the instance of the mutable class).

In above scenario, we have passed Mutable object wherever an Immutable object is expected, which can lead a big trouble while execution of code because we are assuming the object is truly immutable(Problem when this object will use the key of HashMap).


Marking the base class final prevents this from happening.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...