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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With