Why would one declare an immutable class final in Java?

JavaImmutabilityFinal

Java Problem Overview


I read that to make a class immutable in Java, we should do the following,

  1. Do not provide any setters
  2. Mark all fields as private
  3. Make the class final

Why is step 3 required? Why should I mark the class final?

Java Solutions


Solution 1 - Java

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:

public class Immutable {
     private final int value;

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

     public int getValue() {
         return value;
     }
}

Now, suppose I do the following:

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);
	    Immutable immObj = (Immutable)obj;   	    	
	    System.out.println(immObj.getValue());
	    obj.setValue(8);
	    System.out.println(immObj.getValue());
    }
}

Notice that in my Mutable subclass, I've overridden the behavior of getValue to 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 this Mutable object wherever an Immutable object is expected, which could do Very Bad Things to code assuming the object is truly immutable. Marking the base class final prevents this from happening.

Hope this helps!

Solution 2 - Java

Contrary to what many people believe, making an immutable class final is not required.

The standard argument for making immutable classes final is that if you don't do this, then subclasses can add mutability, thereby violating the contract of the superclass. Clients of the class will assume immutability, but will be surprised when something mutates out from under them.

If you take this argument to its logical extreme, then all methods should be made final, as otherwise a subclass could override a method in a way that doesn't conform to the contract of its superclass. It's interesting that most Java programmers see this as ridiculous, but are somehow okay with the idea that immutable classes should be final. I suspect that it has something to do with Java programmers in general not being entirely comfortable with the notion of immutability, and perhaps some sort of fuzzy thinking relating to the multiple meanings of the final keyword in Java.

Conforming to the contract of your superclass is not something that can or should always be enforced by the compiler. The compiler can enforce certain aspects of your contract (eg: a minimum set of methods and their type signatures) but there are many parts of typical contracts that cannot be enforced by the compiler.

Immutability is part of the contract of a class. It's a bit different from some of the things people are more used to, because it says what the class (and all subclasses) can't do, while I think most Java (and generally OOP) programmers tend to think about contracts as relating to what a class can do, not what it can't do.

Immutability also affects more than just a single method — it affects the entire instance — but this isn't really much different than the way equals and hashCode in Java work. Those two methods have a specific contract laid out in Object. This contract very carefully lays out things that these methods cannot do. This contract is made more specific in subclasses. It is very easy to override equals or hashCode in a way that violates the contract. In fact, if you override only one of these two methods without the other, chances are that you're violating the contract. So should equals and hashCode have been declared final in Object to avoid this? I think most would argue that they should not. Likewise, it is not necessary to make immutable classes final.

That said, most of your classes, immutable or not, probably should be final. See Effective Java Second Edition Item 17: "Design and document for inheritance or else prohibit it".

So a correct version of your step 3 would be: "Make the class final or, when designing for subclassing, clearly document that all subclasses must continue to be immutable."

Solution 3 - Java

Don't mark the entire class final.

There are valid reasons for allowing an immutable class to be extended as stated in some of the other answers so marking the class as final is not always a good idea.

It's better to mark your properties private and final and if you want to protect the "contract" mark your getters as final.

In this way you can allow the class to be extended (yes possibly even by a mutable class) however the immutable aspects of your class are protected. Properties are private and can't be accessed, getters for these properties are final and cannot be overridden.

Any other code that uses an instance of your immutable class will be able to rely on the immutable aspects of your class even if the sub class it is passed is mutable in other aspects. Of course, since it takes an instance of your class it wouldn't even know about these other aspects.

Solution 4 - Java

If it's not final then anyone could extend the class and do whatever they like, like providing setters, shadowing your private variables, and basically making it mutable.

Solution 5 - Java

That constraints other classes extending your class.

final class can't be extended by other classes.

If a class extend the class you want to make as immutable, it may change the state of the class due to inheritance principles.

Just clarify "it may change". Subclass can override superclass behaviour like using method overriding (like templatetypedef/ Ted Hop answer)

Solution 6 - Java

If you do not make it final I can extend it and make it non mutable.

public class Immutable {
  privat final int val;
  public Immutable(int val) {
    this.val = val;
  }

  public int getVal() {
    return val;
  }
}

public class FakeImmutable extends Immutable {
  privat int val2;
  public FakeImmutable(int val) {
    super(val);
  }

  public int getVal() {
    return val2;
  }

  public void setVal(int val2) {
    this.val2 = val2;
  }
}

Now, I can pass FakeImmutable to any class that expects Immutable, and it will not behave as the expected contract.

Solution 7 - Java

For creating an immutable class it is not mandatory to mark the class as final.

Let me take one such example from the standard library itself: BigInteger is immutable but it's not final.

Actually, immutability is a concept according to which once an object is created, it can not be modified.

Let's think from the JVM point of view. From the JVM point of view, an object of this class should be fully constructed before any thread can access it and the state of the object shouldn't change after its construction.

Immutability means there is no way to change the state of the object once it is created and this is achieved by three thumb rules which make the compiler recognize that class is immutable and they are as follows:

  • All non-private fields should be final
  • Make sure that there is no method in the class that can change the fields of the object either directly or indirectly
  • Any object reference defined in the class can't be modified from outside of the class

For more information refer to this URL.

Solution 8 - Java

Let's say you have the following class:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PaymentImmutable {
	private final Long id;
	private final List<String> details;
	private final Date paymentDate;
	private final String notes;

	public PaymentImmutable (Long id, List<String> details, Date paymentDate, String notes) {
		this.id = id;
		this.notes = notes;
		this.paymentDate = paymentDate == null ? null : new Date(paymentDate.getTime());
		if (details != null) {
			this.details = new ArrayList<String>();

			for(String d : details) {
				this.details.add(d);
			}
		} else {
			this.details = null;
		}
	}

	public Long getId() {
		return this.id;
	}

	public List<String> getDetails() {
		if(this.details != null) {
			List<String> detailsForOutside = new ArrayList<String>();
			for(String d: this.details) {
				detailsForOutside.add(d);
			}
			return detailsForOutside;
		} else {
			return null;
		}
	}

}

Then you extend it and break its immutability.

public class PaymentChild extends PaymentImmutable {
    private List<String> temp;
    public PaymentChild(Long id, List<String> details, Date paymentDate, String notes) {
        super(id, details, paymentDate, notes);
        this.temp = details;
    }

    @Override
    public List<String> getDetails() {
        return temp;
    }
}

Here we test it:

public class Demo {

    public static void main(String[] args) {
        List<String> details = new ArrayList<>();
        details.add("a");
        details.add("b");
        PaymentImmutable immutableParent = new PaymentImmutable(1L, details, new Date(), "notes");
        PaymentImmutable notImmutableChild = new PaymentChild(1L, details, new Date(), "notes");

        details.add("some value");
        System.out.println(immutableParent.getDetails());
        System.out.println(notImmutableChild.getDetails());
    }
}

Output result will be:

[a, b]
[a, b, some value]

As you can see while original class is keeping its immutability, child classes can be mutable. Consequently, in your design you cannot be sure that the object you are using is immutable, unless you make your class final.

Solution 9 - Java

Suppose the following class were not final:

public class Foo {
    private int mThing;
    public Foo(int thing) {
        mThing = thing;
    }
    public int doSomething() { /* doesn't change mThing */ }
}

It's apparently immutable because even subclasses can't modify mThing. However, a subclass can be mutable:

public class Bar extends Foo {
    private int mValue;
    public Bar(int thing, int value) {
        super(thing);
        mValue = value;
    }
    public int getValue() { return mValue; }
    public void setValue(int value) { mValue = value; }
}

Now an object that is assignable to a variable of type Foo is no longer guaranteed to be mmutable. This can cause problems with things like hashing, equality, concurrency, etc.

Solution 10 - Java

Design by itself has no value. Design is always used to achieve a goal. What is the goal here? Do we want to reduce the amount of surprises in the code? Do we want to prevent bugs? Are we blindly following rules?

Also, design always comes at a cost. Every design that deserves the name means you have a conflict of goals.

With that in mind, you need to find answers to these questions:

  1. How many obvious bugs will this prevent?
  2. How many subtle bugs will this prevent?
  3. How often will this make other code more complex (= more error prone)?
  4. Does this make testing easier or harder?
  5. How good are the developers in your project? How much guidance with a sledge hammer do they need?

Say you have many junior developers in your team. They will desperately try any stupid thing just because they don't know good solutions for their problems, yet. Making the class final could prevent bugs (good) but could also make them come up with "clever" solutions like copying all these classes into a mutable ones everywhere in the code.

On the other hand, it will be very hard to make a class final after it's being used everywhere but it's easy to make a final class non-final later if you find out you need to extend it.

If you properly use interfaces, you can avoid the "I need to make this mutable" problem by always using the interface and then later adding a mutable implementation when the need arises.

Conclusion: There is no "best" solution for this answer. It depends on which price you're willing and which you have to pay.

Solution 11 - Java

The default meaning of equals() is the same as referential equality. For immutable data types, this is almost always wrong. So you have to override the equals() method, replacing it with your own implementation. link

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnandView Question on Stackoverflow
Solution 1 - JavatemplatetypedefView Answer on Stackoverflow
Solution 2 - JavaLaurence GonsalvesView Answer on Stackoverflow
Solution 3 - JavaJustin OhmsView Answer on Stackoverflow
Solution 4 - JavadigitaljoelView Answer on Stackoverflow
Solution 5 - JavakosaView Answer on Stackoverflow
Solution 6 - JavaRoger LindsjöView Answer on Stackoverflow
Solution 7 - JavaTarun BediView Answer on Stackoverflow
Solution 8 - JavavalijonView Answer on Stackoverflow
Solution 9 - JavaTed HoppView Answer on Stackoverflow
Solution 10 - JavaAaron DigullaView Answer on Stackoverflow
Solution 11 - JavaAnitha B SView Answer on Stackoverflow