Run-Time Type Comparisons Within a Generic Hierarchy
The instanceof operator can be applied to objects of generic classes.
class Gen<T> {
T ob;
Gen(T o) {
ob = o;
}
T getob() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
public class Main {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
System.out.println("iOb2 is instance of Gen2"+(iOb2 instanceof Gen2<?>));
System.out.println("iOb2 is instance of Gen"+(iOb2 instanceof Gen<?>));
System.out.println("strOb2 is instance of Gen2"+(strOb2 instanceof Gen2<?>));
System.out.println("strOb2 is instance of Gen"+(strOb2 instanceof Gen<?>));
System.out.println("iOb is instance of Gen2"+(iOb instanceof Gen2<?>));
System.out.println("iOb is instance of Gen"+(iOb instanceof Gen<?>));
}
}
Casting
You can cast one instance of a generic class into another only if the two are compatible and their type arguments are the same.
For example, assuming the foregoing program, this cast is legal:
class Gen<T> {
T ob;
Gen(T o) {
ob = o;
}
T getob() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
public class Main {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
iOb = (Gen<Integer>) iOb2;
}
}
because iOb2 is an instance of Gen<Integer>. But, this cast:
class Gen<T> {
T ob;
Gen(T o) {
ob = o;
}
T getob() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
public class Main {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
//iOb = (Gen<Long>) iOb2;//wrong
}
}
is not legal because iOb2 is not an instance of Gen<Long>.
Home
Java Book
Language Basics
Java Book
Language Basics
Generics:
- Generic Class
- Generic Bounded Types
- Generic Wildcard Arguments
- Generic Bounded Wildcards
- Generic Method
- Generic Constructors
- Generic Interfaces
- Raw Types and Legacy Code
- Generic Class Hierarchies
- Run-Time Type Comparisons Within a Generic Hierarchy
- Overriding Methods in a Generic Class
- Generic Restrictions
- Generic Array Restrictions