Source of LocalCopy.java


  1: //: appendixa:LocalCopy.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: // Creating local copies with clone().
  5: import java.util.*;

  7: class MyObject implements Cloneable {
  8:   int i;
  9:   MyObject(int ii) { i = ii; }
 10:   public Object clone() {
 11:     Object o = null;
 12:     try {
 13:       o = super.clone();
 14:     } catch(CloneNotSupportedException e) {
 15:       System.err.println("MyObject can't clone");
 16:     }
 17:     return o;
 18:   }
 19:   public String toString() {
 20:     return Integer.toString(i);
 21:   }
 22: }

 24: public class LocalCopy {
 25:   static MyObject g(MyObject v) {
 26:     // Passing a reference, 
 27:     // modifies outside object:
 28:     v.i++;
 29:     return v;
 30:   }
 31:   static MyObject f(MyObject v) {
 32:     v = (MyObject)v.clone(); // Local copy
 33:     v.i++;
 34:     return v;
 35:   }
 36:   public static void main(String[] args) {
 37:     MyObject a = new MyObject(11);
 38:     MyObject b = g(a);
 39:     // Testing reference equivalence,
 40:     // not object equivalence:
 41:     if(a == b) 
 42:       System.out.println("a == b");
 43:     else 
 44:       System.out.println("a != b");
 45:     System.out.println("a = " + a);
 46:     System.out.println("b = " + b);
 47:     MyObject c = new MyObject(47);
 48:     MyObject d = f(c);
 49:     if(c == d) 
 50:       System.out.println("c == d");
 51:     else 
 52:       System.out.println("c != d");
 53:     System.out.println("c = " + c);
 54:     System.out.println("d = " + d);
 55:   }
 56: } ///:~