class Mutable
public class Immutable2
1: //: appendixa:Immutable2.java
2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
4: // A companion class for making
5: // changes to immutable objects.
7: class Mutable {
8: private int data;
9: public Mutable(int initVal) {
10: data = initVal;
11: }
12: public Mutable add(int x) {
13: data += x;
14: return this;
15: }
16: public Mutable multiply(int x) {
17: data *= x;
18: return this;
19: }
20: public Immutable2 makeImmutable2() {
21: return new Immutable2(data);
22: }
23: }
25: public class Immutable2 {
26: private int data;
27: public Immutable2(int initVal) {
28: data = initVal;
29: }
30: public int read() { return data; }
31: public boolean nonzero() { return data != 0; }
32: public Immutable2 add(int x) {
33: return new Immutable2(data + x);
34: }
35: public Immutable2 multiply(int x) {
36: return new Immutable2(data * x);
37: }
38: public Mutable makeMutable() {
39: return new Mutable(data);
40: }
41: public static Immutable2 modify1(Immutable2 y){
42: Immutable2 val = y.add(12);
43: val = val.multiply(3);
44: val = val.add(11);
45: val = val.multiply(2);
46: return val;
47: }
48: // This produces the same result:
49: public static Immutable2 modify2(Immutable2 y){
50: Mutable m = y.makeMutable();
51: m.add(12).multiply(3).add(11).multiply(2);
52: return m.makeImmutable2();
53: }
54: public static void main(String[] args) {
55: Immutable2 i2 = new Immutable2(47);
56: Immutable2 r1 = modify1(i2);
57: Immutable2 r2 = modify2(i2);
58: System.out.println("i2 = " + i2.read());
59: System.out.println("r1 = " + r1.read());
60: System.out.println("r2 = " + r2.read());
61: }
62: } ///:~