Java Generics class

Introduction

The following program defines a generic class Gen.

class Gen<T> { 
  private T ob; // declare an object of type T 

  Gen(T o) { //from  ww w  .java 2  s.co  m
    ob = o; 
  } 
 
  // Return ob. 
  public T getob() { 
    return ob; 
  } 
   // Show type of T. 
  void showType() { 
    System.out.println("Type of T is " + 
                       ob.getClass().getName()); 
  } 
} 

public class Main { 
  public static void main(String args[]) { 
    Gen<Integer> iOb = new Gen<Integer>(88); 
    iOb.showType(); 
    int v = iOb.getob(); 
    System.out.println("value: " + v); 
 
    Gen<String> strOb = new Gen<String>("Generics Test"); 
    strOb.showType(); 
    String str = strOb.getob(); 
    System.out.println("value: " + str); 
  } 
}



PreviousNext

Related