Bridge Methods – Generics

Bridge Methods

Bridge methods are inserted in subclasses by the compiler to ensure that overriding of methods works correctly. The canonical example is the implementation of the Comparable interface. The post-erasure code of the class CmpNode<E> from Example 11.8 is shown below. A second compareTo() method has been inserted by the compiler at (2), whose method signature is compareTo(Object). This is necessary because, without this method, the class would not implement the Comparable interface, as the post-erasure compareTo(Object) method of the interface would not be overridden correctly in the erasure code.

Click here to view code image

class CmpNode extends Node implements Comparable {
  CmpNode(Object data, CmpNode next) {
    super(data, next);
  }
  public int compareTo(CmpNode node2) {       // (1) Implemented method erasure
    return this.getData().compareTo(node2.getData());
  }
  public int compareTo(Object node2) {        // (2) Inserted bridge method.
    return this.compareTo((CmpNode)node2);    // Calls the method at (1).
  }
}

11.12 Implications for Overloading and Overriding

Before discussing the implications generics have for overloading and overriding, we need a few definitions regarding method signatures.

Method Signatures Revisited

Method signatures play a crucial role in overloading and overriding of methods. The method signature comprises the method name and the formal parameter list. Two methods (or constructors) have the same signature if both of the following conditions are fulfilled:

  • They have the same name.
  • They have the same formal parameter types.

Two methods (or constructors) have the same formal parameter types if both of the following conditions are fulfilled:

  • They have the same number of formal parameters and type parameters.
  • The formal parameters and the bounds of the type parameters are the same after the occurrences of formal parameters in one are substituted with the corresponding types from the second.

The signature of a method m() is a subsignature of the signature of another method n(), if either one of these two conditions hold:

  • Method n() has the same signature as method m(), or
  • The signature of method m() is the same as the erasure of the signature of method n().

The signatures of the two methods m() and n() are override-equivalent if either one of these two conditions hold:

  • The signature of method m() is a subsignature of the signature of method n(), or
  • The signature of method n() is a subsignature of the signature of method m().

Comments

Leave a Reply

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