私はその本を自分で読んでいます。この例ですべてが「正しく」行われたかどうかはわかりませんが、理解に役立つかもしれません。
コンピューター.java
package testclone;
public class Computer implements Cloneable {
String OperatingSystem;
protected Computer Clone() throws CloneNotSupportedException {
Computer newClone = (Computer) super.clone();
newClone.OperatingSystem = this.OperatingSystem;
return newClone;
}
}
マルチコア.java
package testclone;
public class MultiCore extends Computer implements Cloneable {
int NumberOfCores;
@Override
protected MultiCore Clone() throws CloneNotSupportedException {
//********* use 1 of the next 2 lines ***********
//MultiCore newClone = (MultiCore) super.clone();
MultiCore newClone = new MultiCore();
newClone.NumberOfCores = this.NumberOfCores;
return newClone;
}
}
TestClone.java
package testclone;
public class TestClone implements Cloneable {
public static void main(String[] args) throws CloneNotSupportedException {
//Computer myComputer = new Computer();
//myComputer.OperatingSystem = "Windows";
MultiCore myMultiCore = new MultiCore();
myMultiCore.OperatingSystem = "Windows"; //field is in parent class
myMultiCore.NumberOfCores = 4;
MultiCore newMultiCore = myMultiCore.Clone();
System.out.println("orig Operating System = " + myMultiCore.OperatingSystem);
System.out.println("orig Number of Cores = " + myMultiCore.NumberOfCores);
System.out.println("clone Operating System = " + newMultiCore.OperatingSystem);
System.out.println("clone Number of Cores = " + newMultiCore.NumberOfCores);
}
}
出力:
元のオペレーティング システム = Windows
元のコア数 = 4
clone Operating System = null * この行は必要なものではありません。
clone コア数 = 4
代わりに super.clone() 行を使用すると、出力は
元のオペレーティング システム = Windows
元のコア数 = 4
clone オペレーティング システム = Windows * 今、あなたが望むものです
clone コア数 = 4
したがって、super.clone() を使用しない場合、親 (または祖父母、曽祖父母など) のフィールドは複製されません。
幸運を!(申し訳ありませんが、入力したときは正しくフォーマットされているように見えましたが、実際に表示すると何らかの理由でひどく見えます)