Java Reference
In-Depth Information
Type Erasure
Specifying a generic type allows the compiler to enforce proper use of the generic type.
For example, specifying the generic type of a Cupboard as String is like replacing the T in
the Cupboard class with String :
Cupboard<String> c1 = new Cupboard<String>(“dishes”);
However, behind the scenes, the compiler replaces all references to T in Cupboard with
Object . In other words, after the code compiles, your generics are actually just Object
types. The Cupboard class looks like the following output:
public class Cupboard {
private Object item;
public Cupboard(Object item) {
System.out.println(“Cupboard for “ + item.getClass());
this.item = item;
}
public Object getItem() {
return item;
}
}
Displaying item.getClass() doesn't simply output Object each time due to
polymorphism. The class name displayed is the actual data type that the fi eld item refers
to. Also, if getItem returns an Object , a cast is needed at runtime. The compiler adds the
appropriate cast for you whenever you invoke getItem .
This process of removing the generics syntax from your code is referred to as type
erasure . Type erasure allows your code to be compatible with older versions of Java that
did not contain generics.
As with classes, you can use generics in interface declarations, which I discuss in the
next section.
Generic Interfaces
An interface can declare a formal type parameter in the same fashion as a class. For example,
the following Breakable interface uses a generic type as the argument to its doBreak method:
public interface Breakable<T> {
public void doBreak(T t);
}
Search WWH ::




Custom Search