You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 11 Next »

This is a stub. It needs an example of an error caused due to using the Base class's object where the subclass's object was expected. It should not produce a RuntimeException (ClassCastException) to qualify.

class Base implements Cloneable {
  public Object clone() throws CloneNotSupportedException {
    return new Base();	 
  }
  protected static void doLogic() {
    System.out.println("Superclass doLogic");
  }
}

class Subclass1 extends Base {
  public Object clone() throws CloneNotSupportedException {
    return super.clone();
  }
  protected static void doLogic() {
    System.out.println("Subclass doLogic");
  }
  public static void main(String[] args) {
    Subclass1 s = new Subclass1();
    try {
      Object sc = s.clone(); // get's Base obj instead of subclass'
      System.out.println(sc.getClass().hashCode()); // a possible mistake
      // ((Subclass1)sc).doLogic(); // Produces ClassCastException, disqualified
    } catch (CloneNotSupportedException e) { /* ... */ }
  }
}

MET14-J. Follow the general contract when implementing the compareTo method      12. Methods (MET)      MET36-J. Do not use deprecated or obsolete methods

  • No labels