Ans
The following rules define simple strategy for create
immutable object:
Ø
Make the class final.
Ø
Don’t provide “setter” methods –methods that
modify fields or object referred by fields.
Ø
Make all fields final and private.
Ø
Don’t allow sub class to override methods, the
simple way to do this is to declare class as final.
Ø
Don’t provide methods that modify the mutable
objects.
Example:
public
final class Persson {
private final String name;
private final int age;
private final
Collection<String> friends;
public Persson(final String
name, int age, Collection<String> friends) {
// TODO Auto-generated
constructor stub
this.name = name;
this.age = age;
this.friends= new
ArrayList(this.friends);
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Collection<String>
getFriends() {
return friends;
}
public static void
main(String[] args) {
Persson ps = new
Persson(null, 0, null);
}
}