Snippet of an Immutable Class
A class whose attributes remain same once after instantiation of that particular object.
/* 1- Make your class
final, so that no other classes can extend it */
public final class StudentImmutableClass {
/* 2- Make all your
fields final, so that they’re initialized only once inside the constructor and
never modified afterwards */
private final int rollNo;
private final String name;
private final Age age;
/* 3- If the class
holds a mutable object:
* Inside the constructor, make sure to use a
clone copy of the passed argument and never set your mutable field to the real instance passed through constructor, this is
to prevent the clients who pass the object from modifying it afterwards.
* Make sure to always return a clone copy of
the field and never return the real object instance
*/
public StudentImmutableClass(int rollNo, String name, Age age) {
this.rollNo = rollNo;
this.name = name;
this.age = getClone(age);
}
Age getClone(Age age) {
Age ageClone = new Age();
ageClone.setDate(age.getDate());
ageClone.setMonth(age.getMonth());
ageClone.setYear(age.getYear());
return ageClone;
}
/* 4- Don’t expose
setter methods */
/* When exposing methods which modify the state of the class, you must always return a new
instance of the class */
public int getRollNo() {
return rollNo;
}
public String getName() {
return name;
}
public Age getAge() {
return age;
}
}
Muttable class - Age.java
public class Age {
int date;
int month;
int year;
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
Client calling Immutable class
public class TestImmutableClass {
public static void main(String[] args) {
Age age = new Age();
age.setDate(1);
age.setMonth(1);
age.setYear(1992);
/* Make sure that constructor return a clone of muttable object
and not actual object */
StudentImmutableClass
student = new StudentImmutableClass(1, "Alex", age);
System.out.println("Alex age year before modification = " + student.getAge().getYear());
age.setYear(1993);
System.out.println("Alex age year after modification = " + student.getAge().getYear());
}
}
References
http://programmergate.com/create-immutable-class-java/
No comments:
Post a Comment