This question is about good programming practices and avoiding potential holes.
I read Joshua Bloch\'s Effective Java and here is what I wonder:
Why should I conside
I slightly modified Tomasz Nurkiewicz answer, to demonstrate why making dateOfBirth final does not defend it from being changed by a client class:
public class Immutable {
private final String name;
private final Date dateOfBirth;
public Immutable(String name, Date dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
}
public String getName() { return name; }
public Date getDateOfBirth() { return dateOfBirth; }
public static void main(String[] args) {
//create an object
Immutable imm = new Immutable("John", new Date());
System.out.println(imm.getName() + " " + imm.getDateOfBirth());
//try and modify object's intenal
String name = imm.getName(); //safe because Integer is immutable
name = "George"; //has no effect on imm
Date dateOfBirth = imm.getDateOfBirth();
dateOfBirth.setTime(0); //we just modified `imm` object
System.out.println(imm.getName() + " " + imm.getDateOfBirth());
}
}
**Output:**
John Wed Jan 13 11:23:49 IST 2016
John Thu Jan 01 02:00:00 IST 1970