Creating read-only classes
It’s possible to create your own read-only class. Here’s an example:
//: appendixa:Immutable1.java
// Objects that cannot be modified are immune to aliasing.
import com.bruceeckel.simpletest.*;
public class Immutable1 {
private static Test monitor = new Test();
private int data;
public Immutable1(int initVal) {
data = initVal;
}
public int read() { return data; }
public boolean nonzero() { return data != 0; }
public Immutable1 multiply(int multiplier) {
return new Immutable1(data * multiplier);
}
public static void f(Immutable1 i1) {
Immutable1 quad = i1.multiply(4);
System.out.println("i1 = " + i1.read());
System.out.println("quad = " + quad.read());
}
public static void main(String[] args) {
Immutable1 x = new Immutable1(47);
System.out.println("x = " + x.read());
f(x);
System.out.println("x = " + x.read());
monitor.expect(new String[] {
"x = 47",
"i1 = 47",
"quad = 188",
"x = 47"
});
}
} ///:~
All data is private, and you’ll see that none of the public methods modify that data. Indeed, the method that does appear to modify an object is multiply( ), but this creates a new Immutable1 object and leaves the original one untouched.
The method f( ) takes an Immutable1 object and performs various operations on it, and the output of main( ) demonstrates that there is no change to x. Thus, x’s object could be aliased many times without harm, because the Immutable1 class is designed to guarantee that objects cannot be changed.