Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a non-final class be fully immutable?

Can a class that does not have final modifier in it be fully immutable ?

For example, is the following class immutable ?

class Animal
{
    private String animalName;

    public Animal(String name) {
        animalName = name;
    }

    public String getName() { return animalName; }
}
like image 420
user2434 Avatar asked Mar 08 '26 12:03

user2434


2 Answers

Yes.

The class (as depicted in your question) is immutable, as none of its internal state may be changed. Even if you were to define a subclass of the Animal class, it could not change animalName; however, while the Animal class is immutable, its subclasses may or not be immutable (depending on their implementation).

The danger of doing this is that if someone were to define a subclass as an inner class within the Animal class (as follows), then they could violate your immutability:

class Animal {
    private String animalName;
    public Animal(String name) {
        animalName = name;
    }
    public getName() { return animalName; }

    public class Eagle extends Animal {
        public Eagle() {
            super("Eagle");
        }
        public void foo() {
            animalName = animalName + "!";
        }
    }
}

For this reason, it's great to use private visibility and the final modifier, wherever possible. This will prevent people from accidentally introducing code that violates immutability or encapsulation constraints that you have meant to impose. That way, it must be a conscious decision on the programmer's part to increase the visibility or remove the final keyword, and therefore they shall not introduce any "accidents" as described above.

like image 95
Jon Newmuis Avatar answered Mar 10 '26 00:03

Jon Newmuis


Yes. It is fully immutable. Or to be more precise, its instances are fully immutable.

There can (of course) be subclasses that are not immutable ... but that does not affect the mutability of an instance of the Animal class.

like image 32
Stephen C Avatar answered Mar 10 '26 01:03

Stephen C