Immutable Objects and Classes

RMAG news

You can define immutable classes to create immutable objects. The contents of immutable objects cannot be changed. Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as immutable object and its class as immutable class. The String class, for example, is immutable. If you deleted the setter method in the
CircleWithPrivateDataFields class, the class would be immutable, because radius is private and cannot be changed without a setter method.

If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable. For example, the following Student class has all private data fields and no setter methods, but it is not an immutable class.

public class Student {
private int id;
private String name;
private java.util.Date dateCreated;

public Student(int ssn, String newName) {
id = ssn;
name = newName;
dateCreated = new java.util.Date();
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public java.util.Date getDateCreated() {
return dateCreated;
}
}

As shown in the following code, the data field dateCreated is returned using the getDateCreated() method. This is a reference to a Date object. Through this reference, the content for dateCreated can be changed.

public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, “John”);
java.util.Date dateCreated = student.getDateCreated();
dateCreated.setTime(200000); // Now dateCreated field is changed!
}
}

For a class to be immutable, it must meet the following requirements:

All data fields must be private.
There can’t be any mutator methods for data fields.
No accessor methods can return a reference to a data field that is mutable