Monday 10 March 2014

Generic Class

A generic class is defined with the following format:

class name<T1, T2, ..., Tn> { /* ... */ }

The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

A type variable “T” can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

class GenericClassEx<T1, T2, T3>{
 T1 var1;
 T2 var2;
 T3 var3;

 GenericClassEx(T1 var1, T2 var2, T3 var3){
  this.var1 = var1;
  this.var2 = var2;
  this.var3 = var3;
 }

 public void print(){
  System.out.println(var1 +"\t"+var2+"\t"+var3);
 }

 public static void main(String args[]){
  System.out.println("Object \t var1 \t var2 \t var3");
  GenericClassEx<Integer, String, Double> obj1 = new GenericClassEx<>(10, "ABCD", 10.11);
  System.out.print("Obj1\t");

  obj1.print();
  GenericClassEx<String, String, Double> obj2 = new GenericClassEx<>("EFGH", "ABCD", 9.11);
  System.out.print("Obj2\t");

  obj2.print();
  GenericClassEx<String, String, String> obj3 = new GenericClassEx<>("EFGH", "ABCD", "IJKL");
  System.out.print("Obj3\t");
  obj3.print();
 }
}
   
Output
Object var1 var2 var3
Obj1 10 ABCD 10.11
Obj2 EFGH ABCD 9.11
Obj3 EFGH ABCD IJKL
   
GenericClassEx<Integer, String, Double> obj1 = new GenericClassEx<>(10, "ABCD", 10.11);
Here
   T1 represents the type Integer,
   T2 represents the type String,
   T3 represents the type Double

GenericClassEx<String, String, Double> obj2 = new GenericClassEx<>("EFGH", "ABCD",9.11);
Here
   T1 represents the type String,
   T2 represents the type String,
   T3 represents the type Double

GenericClassEx<String, String, String> obj3 = new GenericClassEx<>("EFGH", "ABCD", "IJKL");
Here
   T1 represents the type String,
   T2 represents the type String,
   T3 represents the type String




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment