I'm reading that book myself. Not sure if I did everything "right" in this example, but maybe it'll help you understand.
Computer.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;
}
}
MultiCore.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);
}
}
Output:
orig Operating System = Windows
orig Number of Cores = 4
clone Operating System = null * This line is not what you want.
clone Number of Cores = 4
If you use the super.clone() line instead, then the Output is
orig Operating System = Windows
orig Number of Cores = 4
clone Operating System = Windows * Now it's what you want
clone Number of Cores = 4
So if you don't use super.clone(), it doesn't clone the fields in the parent (or grandparent, or great-grandparent, etc)
Good luck!
(Sorry - the above looked formatted correctly when I typed it in, but for some reason looks awful when it actually shows)