Java Generic Class

Generic Class:
A class that can refer to any type is known as generic class. Here, we are using T type parameter to create the generic class of specific type.
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you specify for the class, will be used to store and retrieve the data.

Code:

  1. public class GenericTest<T> {  
  2.       
  3.     T obj;  
  4.     public GenericTest(T obj) {  
  5.         // TODO Auto-generated constructor stub  
  6.         this.obj=obj;  
  7.     }  
  8.       
  9.     public T getObject(){  
  10.         return this.obj;  
  11.     }  
  12.   
  13. }  
  14.   
  15.   
  16. //Main class  
  17.   
  18.   
  19. public class GenericDemo {  
  20.   
  21.     public static void main(String[] args) {  
  22.         // TODO Auto-generated method stub  
  23.           
  24.         GenericTest<Integer>iobj=new GenericTest<Integer>(100);  
  25.         System.out.println(iobj.getObject());  
  26.           
  27.         GenericTest<String>sobj=new GenericTest<String>("Lict");  
  28.         System.out.println(sobj.getObject());  
  29.   
  30.     }  
  31.   
  32. }  
Share:

0 Comments:

Post a Comment