Java Reference
In-Depth Information
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.
Student class
1 public class Student {
2
private int id;
3
private String name;
4
private java.util.Date dateCreated;
5
6 public Student( int ssn, String newName) {
7 id = ssn;
8 name = newName;
9 dateCreated = new java.util.Date();
10 }
11
12
public int getId() {
13
return id;
14 }
15
16
public String getName() {
17
return name;
18 }
19
20
public java.util.Date getDateCreated() {
21
return dateCreated;
22 }
23 }
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.
Interested readers may refer to Supplement III.U for an extended discussion on immutable objects.
9.28
If a class contains only private data fields and no setter methods, is the class immutable?
Check
9.29
If all the data fields in a class are private and of primitive types, and the class doesn't
contain any setter methods, is the class immutable?
Point
9.30
Is the following class immutable?
public class A {
private int [] values;
public int [] getValues() {
 
 
Search WWH ::




Custom Search