352 Part I: The Java Language
}// A subclass of Gen.
class Gen2 extends Gen<String> {Gen2(String o) {
super(o);
}// A String-specific override of getob().
String getob() {
System.out.print("You called String getob(): ");
return ob;
}
}// Demonstrate a situation that requires a bridge method.
class BridgeDemo {
public static void main(String args[]) {// Create a Gen2 object for Strings.
Gen2 strOb2 = new Gen2("Generics Test");System.out.println(strOb2.getob());
}
}In the program, the subclassGen2extendsGen, but does so using aString-specific version
ofGen, as its declaration shows:class Gen2 extends Gen<String> {Furthermore, insideGen2,getob( )is overridden withStringspecified as the return type:// A String-specific override of getob().
String getob() {
System.out.print("You called String getob(): ");
return ob;
}All of this is perfectly acceptable. The only trouble is that because of type erasure, the
expected form ofgetob( )will beObject getob() { // ...To handle this problem, the compiler generates a bridge method with the preceding signature
that calls theStringversion. Thus, if you examine the class file forGen2by usingjavap, you
will see the following methods:class Gen2 extends Gen{
Gen2(java.lang.String);
java.lang.String getob();
java.lang.Object getob(); // bridge method
}