Monday, 10 March 2014

Generics

Generics is a Java feature supported from Java 1.5, used to implement Generic types and Generic methods.

Will see the simple example, to display a data of type integer, float, double, string variable, which is passed to a method print.

Example 1: Without generics
class PrintData{
 void print(int var){
  System.out.println(var);
 }

 void print(float var){
  System.out.println(var);
 }

 void print(double var){
  System.out.println(var);
 }

 void print(String var){
  System.out.println(var);
 }

 public static void main(String args[]){
  PrintData obj = new PrintData();
  obj.print(10);
  obj.print("I am a string");
 }
}

Output
10
I am a string
   
Example 2: With generics
class PrintData<T>{
 void print(T var){
  System.out.println(var);
 }

 public static void main(String args[]){
  PrintData<Integer> obj1 = new PrintData<Integer> ();
  PrintData<String> obj2 = new PrintData<String> ();
  obj1.print(10);
  obj2.print("I am a string");
 }
}

Output
10
I am a string

As you obseve the program, T is a type variable, Which is used to create specific type objects.

PrintData<Integer> obj1 = new PrintData<Integer> ();
In this definition, 'T' is replaced with Integer, so the method print will be like below
    print(Integer var)

PrintData<String> obj1 = new PrintData<String> ();
In this definition, 'T' is replaced with String, so the method print will be like below
    print(String var)

Java takes care of all these conversions, This is a simple example, with Generics many bugs are detected at compile time. Reduces the programming effort. All collections supports Generics.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment