You haven't written a immutable class because the final
modifier for the class is missing.
Or you need a final
modifier for the methods getName()
and getDob()
so that this fields are immutable.
In your example it's still possible to "modify" the class with a subclass. For example:
public class EditablePerson extends Person {
// create new fields for name and dob
// this is possible because the private fields of the superclass are not visible
private String name;
private Date dob;
public EditablePerson(String name,Date dob){
// call the constructor of the super-class with dummy-data
super("garbage", null);
this.name=name;
this.dob=dob;
}
@Override
public String getName(){
System.out.println("in person :"+name);
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Date getDob(){
System.out.println("in person :"+dob);
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
To test this:
Person p=new EditablePerson("P", new Date());
p.getName();
if(p instanceof EditablePerson) {
((EditablePerson)p).setName("Changed");
}
p.getName();
As @Tom noted:
The class Person is also not immutable because it has a field with a mutable class (the class Date
is mutable) which can be changed from the outside.
Here the example:
Person p=new Person("P",new Date());
p.getDob();
p.getDob().setTime(0l);
p.getDob()
Also read: A Strategy for Defining Immutable Objects