}
// 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 subclass Gen2 extends Gen, but does so using a String-specific version
of Gen, as its declaration shows:
class Gen2 extends Gen<String> {
Furthermore, inside Gen2, getob( ) is overridden with String specified 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 of getob( ) will be
Object getob() { // ...
To handle this problem, the compiler generates a bridge method with the preceding signature
that calls the String version. Thus, if you examine the class file for Gen2 by using javap, you
will see the following methods:
class Gen2 extends Gen{
Gen2(java.lang.String);
java.lang.String getob();
java.lang.Object getob(); // bridge method
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home