Source of HorrorFlick.java


  1: //: appendixa:HorrorFlick.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: // You can insert Cloneability 
  5: // at any level of inheritance.
  6: import java.util.*;

  8: class Person {}
  9: class Hero extends Person {}
 10: class Scientist extends Person 
 11:     implements Cloneable {
 12:   public Object clone() {
 13:     try {
 14:       return super.clone();
 15:     } catch(CloneNotSupportedException e) {
 16:       // this should never happen:
 17:       // It's Cloneable already!
 18:       throw new InternalError();
 19:     }
 20:   }
 21: }
 22: class MadScientist extends Scientist {}

 24: public class HorrorFlick {
 25:   public static void main(String[] args) {
 26:     Person p = new Person();
 27:     Hero h = new Hero();
 28:     Scientist s = new Scientist();
 29:     MadScientist m = new MadScientist();

 31:     // p = (Person)p.clone(); // Compile error
 32:     // h = (Hero)h.clone(); // Compile error
 33:     s = (Scientist)s.clone();
 34:     m = (MadScientist)m.clone();
 35:   }
 36: } ///:~