Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a public class with getters only an Immutable class?

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;
    }

}
like image 978
user3525139 Avatar asked Mar 20 '23 21:03

user3525139


2 Answers

@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) :

  • the class should be final, or have final methods to prevent subclasses to make instances appears like the state has changed.
  • all fields should be final to get proper thread-safety

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;
    }
}
like image 113
Snicolas Avatar answered Apr 01 '23 11:04

Snicolas


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.

like image 44
Steve Kuo Avatar answered Apr 01 '23 13:04

Steve Kuo