type information available at run time. Therefore, there is no way for instanceof to know if
iOb2 is an instance of Gen2<Integer> or not.
Casting
You can cast one instance of a generic class into another only if the two are otherwise
compatible and their type arguments are the same. For example, assuming the foregoing
program, this cast is legal:
(Gen<Integer>) iOb2 // legal
because iOb2 is an instance of Gen<Integer>. But, this cast:
(Gen<Long>) iOb2 // illegal
is not legal because iOb2 is not an instance of Gen<Long>.
Overriding Methods in a Generic Class
A method in a generic class can be overridden just like any other method. For example,
consider this program in which the method getob( ) is overridden:
// Overriding a generic method in a generic class.
class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
System.out.print("Gen's getob(): " );
return ob;
}
}
// A subclass of Gen that overrides getob().
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
// Override getob().
T getob() {
System.out.print("Gen2's getob(): ");
return ob;
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home