img
// Demonstrate generic method override.
class OverrideDemo {
public static void main(String args[]) {
// Create a Gen object for Integers.
Gen<Integer> iOb = new Gen<Integer>(88);
// Create a Gen2 object for Integers.
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
// Create a Gen2 object for Strings.
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
System.out.println(iOb.getob());
System.out.println(iOb2.getob());
System.out.println(strOb2.getob());
}
}
The output is shown here:
Gen's getob(): 88
Gen2's getob(): 99
Gen2's getob(): Generics Test
As the output confirms, the overridden version of getob( ) is called for objects of type Gen2,
but the superclass version is called for objects of type Gen.
Erasure
Usually, it is not necessary to know the details about how the Java compiler transforms
your source code into object code. However, in the case of generics, some general
understanding of the process is important because it explains why the generic features work
as they do--and why their behavior is sometimes a bit surprising. For this reason, a brief
discussion of how generics are implemented in Java is in order.
An important constraint that governed the way that generics were added to Java was
the need for compatibility with previous versions of Java. Simply put, generic code had to
be compatible with preexisting, non-generic code. Thus, any changes to the syntax of the
Java language, or to the JVM, had to avoid breaking older code. The way Java implements
generics while satisfying this constraint is through the use of erasure.
In general, here is how erasure works. When your Java code is compiled, all generic type
information is removed (erased). This means replacing type parameters with their bound
type, which is Object if no explicit bound is specified, and then applying the appropriate
casts (as determined by the type arguments) to maintain type compatibility with the types
specified by the type arguments. The compiler also enforces this type compatibility. This
approach to generics means that no type parameters exist at run time. They are simply a
source-code mechanism.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home