若新建一個類,它的基礎類會默認為Object,並默認為不具備克隆能力(就象在下一節會看到的那樣)。只要不明確地添加克隆能力,這種能力便不會自動產生。但我們可以在任何層添加它,然後便可從那個層開始向下具有克隆能力。如下所示:
//: HorrorFlick.java
// You can insert Cloneability at any
// level of inheritance.
import java.util.*;
class Person {}
class Hero extends Person {}
class Scientist extends Person
implements Cloneable {
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// this should never happen:
// It's Cloneable already!
throw new InternalError();
}
}
}
class MadScientist extends Scientist {}
public class HorrorFlick {
public static void main(String[] args) {
Person p = new Person();
Hero h = new Hero();
Scientist s = new Scientist();
MadScientist m = new MadScientist();
// p = (Person)p.clone(); // Compile error
// h = (Hero)h.clone(); // Compile error
s = (Scientist)s.clone();
m = (MadScientist)m.clone();
}
} ///:~
添加克隆能力之前,編譯器會阻止我們的克隆嘗試。一旦在Scientist裡添加了克隆能力,那麼Scientist以及它的所有“後裔”都可以克隆。