Source of Snake.java


  1: //: appendixa:Snake.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: // Tests cloning to see if destination
  5: // of references are also cloned.

  7: public class Snake implements Cloneable {
  8:   private Snake next;
  9:   private char c;
 10:   // Value of i == number of segments
 11:   Snake(int i, char x) {
 12:     c = x;
 13:     if(--i > 0)
 14:       next = new Snake(i, (char)(x + 1));
 15:   }
 16:   void increment() {
 17:     c++;
 18:     if(next != null)
 19:       next.increment();
 20:   }
 21:   public String toString() {
 22:     String s = ":" + c;
 23:     if(next != null)
 24:       s += next.toString();
 25:     return s;
 26:   }
 27:   public Object clone() {
 28:     Object o = null;
 29:     try {
 30:       o = super.clone();
 31:     } catch(CloneNotSupportedException e) {
 32:       System.err.println("Snake can't clone");
 33:     }
 34:     return o;
 35:   }
 36:   public static void main(String[] args) {
 37:     Snake s = new Snake(5, 'a');
 38:     System.out.println("s = " + s);
 39:     Snake s2 = (Snake)s.clone();
 40:     System.out.println("s2 = " + s2);
 41:     s.increment();
 42:     System.out.println(
 43:       "after s.increment, s2 = " + s2);
 44:   }
 45: } ///:~