Is the following class immutable? If not, why?
How can I change the fields?
public class Student {
private String name;
private String age;
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
@fge answer might be more complete. But I don't know of immutable having to be thread-safe. For me they are different properties, even though linking them makes sense.
Nevertheless, for the mutability aspect of being immutable, yes, your class is.
Indeed, I don't know if the concept exists, but I would say that your class is "deeply immutable" : not only you can't change the references of its attributes (which I would call shallow immutability
), but you can't change the values of its attributes neither as they are themselves immutable.
----UPDATE
I am wrong.
I read the definition given in Effective Java by Joshua Bloch, and the following is missing (mentionned by others) :
So a correct answer is :
public final class Student {
private final String name;
private final String age;
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
It's not immutable as it could be subclassed (neither the class nor getters are final). A subclass could override the getters and exposing state that could change. Another class holding a reference to Student
has no assurance that its state can't change, since there could be mutable subclass.
Unrelated is that the fields are not final or volatile. Thus there's no guarantee that another thread will see the latest value.
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