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; }
}
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
Animalclass, it could not changeanimalName; however, while theAnimalclass 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
Animalclass (as follows), then they could violate your immutability:For this reason, it’s great to use
privatevisibility and thefinalmodifier, 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 thefinalkeyword, and therefore they shall not introduce any “accidents” as described above.