Implications for Overloading – Generics

Implications for Overriding

The following conditions (referred to as override criteria) should be satisfied in order for a subtype method to override a supertype method:

  • The signature of the subtype method is a subsignature of the signature of the supertype method (which is discussed in this subsection).
  • Their return types should be compatible.
  • Their throws clauses should be compatible (§7.5, p. 388).

Here we discuss the implication of method signatures for overriding.

The @Override Annotation

We can solicit the aid of the compiler to ensure that a method declaration in a subtype correctly overrides a method from its supertype. If a method declaration is preceded by the annotation @Override (§25.5, p. 1578), the compiler will issue an error if the method in the subtype does not override a method from its supertype. The examples in this book make heavy use of this annotation.

Example 11.12 illustrates the use of this annotation. The intention in the class CmpNode is to override the equals() method from the Object class and the compareTo() method from the Comparable interface. The error messages alert us to the fact that the annotated methods do not override any methods. The method signatures are not subsignatures of any methods that are inherited. The formal parameters are not correct for overriding at (1) and (2). Correct method headers are shown at (1′) and (2′).

Example 11.12 Using the @Override Annotation

Click here to view code image

class CmpNode<E extends Comparable<E>> extends Node<E>
                                       implements Comparable<CmpNode<E>> {
  CmpNode(E data, CmpNode<E> next) { super(data, next); }
  @Override
  public boolean equals(CmpNode node2) {           // (1) Compile-time error.
//public boolean equals(Object node2) {            // (1′) Correct header.
    return this.compareTo(node2) == 0;
  }
  @Override
  public int compareTo(Object node2) {              // (2) Compile-time error.
//public int compareTo(CmpNode<E> node2) {          // (2′) Correct header
    return this.getData().compareTo(node2.getData());
  }
}

Compiling the class CmpNode:

Click here to view code image

>
javac CmpNode.java

CmpNode.java:8: method does not override or implement a method from a supertype
  @Override
  ^

CmpNode.java:14: method does not override or implement a method from a supertype
  @Override
  ^

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *