新建類別預設繼承 Object 且無複製能力。可在任一繼承層級加入複製能力,之後所有子類自動擁有:
//: HorrorFlick.java
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) {
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(); // 編譯錯誤
// h = (Hero)h.clone(); // 編譯錯誤
s = (Scientist)s.clone(); // OK
m = (MadScientist)m.clone(); // OK
}
} ///:~
在 Scientist 加入 Cloneable 並覆寫 clone() 後,Scientist 及其所有「後代」(MadScientist)均可複製。基類 Person、Hero 仍不可複製(編譯器阻擋)。
此機制允許在繼承樹中任意層級「開啟」複製能力,向下傳遞,向上不影響。