Java Reference
In-Depth Information
protected void doLogic() {
System.out.println("Superclass doLogic");
}
}
class Derived extends Base {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
protected void doLogic() {
System.out.println("Subclass doLogic");
}
public static void main(String[] args) {
Derived dev = new Derived();
try {
Base devClone = (Base)dev.clone(); // Has type Base
// instead of Derived
devClone.doLogic(); // Prints "Superclass doLogic"
// instead of "Subclass doLogic"
} catch (CloneNotSupportedException e) { /* ... */ }
}
}
Consequently, the object devClone ends up being of type Base instead of Derived ,
and the doLogic() method is incorrectly applied.
Compliant Solution
Thiscompliantsolutioncorrectlycalls super.clone() inthe Base class's clone() meth-
od.
Click here to view code image
class Base implements Cloneable {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
protected void doLogic() {
System.out.println("Superclass doLogic");
}
}
class Derived extends Base {
public Object clone() throws CloneNotSupportedException {
return super.clone();
Search WWH ::




Custom Search