Run-Time Type Comparisons Within a Generic Hierarchy : Generic Class Hierarchies « Generics « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » Generics » Generic Class Hierarchies 
12.7.4.Run-Time Type Comparisons Within a Generic HierarchyPrevious/Next

The run-time type information operator instanceof: determines if an object is an instance of a class. The instanceof operator can be applied to objects of generic classes.

class Gen<T> {  
  T ob; 
    
  Gen(T o) {  
    ob = o;  
  }  
  
  T getObject() {  
    return ob;  
  }  
}  
 
class Gen2<T> extends Gen<T> 
  Gen2(T o) { 
    super(o)
  

 
public class MainClass {  
  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");  
 
    if(iOb2 instanceof Gen2<?>){  
      System.out.println("iOb2 is instance of Gen2")
    }
    if(iOb2 instanceof Gen<?>){  
      System.out.println("iOb2 is instance of Gen")
    }
    if(strOb2 instanceof Gen2<?>){  
      System.out.println("strOb is instance of Gen2")
    }
    if(strOb2 instanceof Gen<?>){  
      System.out.println("strOb is instance of Gen")
    }
    if(iOb instanceof Gen2<?>){  
      System.out.println("iOb is instance of Gen2")
    }
    if(iOb instanceof Gen<?>){  
      System.out.println("iOb is instance of Gen")
    }
    // The following can't be compiled because 
    // generic type info does not exist at runtime.
//    if(iOb2 instanceof Gen2<Integer>)  
//      System.out.println("iOb2 is instance of Gen2<Integer>"); 
  }  
}
iOb2 is instance of Gen2
iOb2 is instance of Gen
strOb is instance of Gen2
strOb is instance of Gen
iOb is instance of Gen
12.7.Generic Class Hierarchies
12.7.1.Generic Class Hierarchies: uses a generic superclass
12.7.2.A subclass can add its own type parameters, if needed.
12.7.3.A Generic Subclass: a nongeneric class can be the superclass of a generic subclass
12.7.4.Run-Time Type Comparisons Within a Generic Hierarchy
12.7.5.Casting within a generic class hierarchy
12.7.6.Overriding Methods in a Generic Class
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.