Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
class Base implements Cloneable {
  public Object clone() throws CloneNotSupportedException {
    return new Base();	 
  }
  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(); // hasHas type Base instead of Derived
      devClone.doLogic();  // printsPrints "Superclass doLogic" instead of "Subclass doLogic"
    } catch (CloneNotSupportedException e) { /* ... */ }
  }
}

...

This compliant solution correctly calls super.clone() in the Base class's clone() method.:

Code Block
bgColor#ccccff
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();
  }
  protected void doLogic() {
    System.out.println("Subclass doLogic");
  }
  public static void main(String[] args) {
    Derived dev = new Derived();
    try {
      Base devClone = (Base)dev.clone(); // hasHas type Derived, as expected
      devClone.doLogic();  // printsPrints "Subclass doLogic", as expected
    } catch (CloneNotSupportedException e) { /* ... */ }
  }
}

...