If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class . If you delete the set method in the Circle3 class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method.
A class with all private data fields and no mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable.
public class Student { private int id; private BirthDate birthDate; public Student( int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } public class BirthDate { private int year; private int month; private int day; public BirthDate( int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear( int newYear) { year = newYear; } }
As shown in the following code, the data field birthDate is returned using the getBirthDate() method. This is a reference to a BirthDate object. Through this reference, the year of the birth date is changed, which effectively changes the contents of the Student object.
public class Test { public static void main(String[] args) { Student student = new Student( 111223333 , 1970 , 5 , 3 ); BirthDate date = student.getBirthDate(); date.setYear( 2010 ); //Now the student birth year is changed! } }
For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.