Thursday, July 21, 2016

JAVA Generics

Java Generics is similar to C++ Templates. You can write a code with Generics for methods, classes and interfaces. Let see one by one. 

Generics Class
To create Generics class we have to use < >. The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

To know more please visit here. Ok,

Example code:

// Use < > to specify Parameter type
class JavaHit<T>
{
 // An object of type T is declared
 T obj;
 JavaHit(T obj) { this.obj = obj; } // constructor part
 public T getObject() { return this.obj; }
}

//To test above I used this class
class Main
{
 public static void main (String[] args)
 {
  // For Integer type
  JavaHit <Integer> integerObj = new JavaHit<Integer>(37);
  System.out.println(integerObj.getObject());

  // For String type
  JavaHit <String> stringObj = new JavaHit<String>("TestForString");
  System.out.println(stringObj.getObject());
 }
}

Output:
37
TestForString

From the above code , you able to understand you can pass any wrapper like Integer , Float etc.,

Multiple Type Parameters

// Use < > to specify Parameter type
class JavaHit<T, U>
{
 T obj1; // An object of type T
 U obj2; // An object of type U

 // constructor
 JavaHit(T obj1, U obj2)
 {
  this.obj1 = obj1;
  this.obj2 = obj2;
 }

 // To print objects of T and U
 public void print()
 {
  System.out.println(obj1);
  System.out.println(obj2);
 }
}

// To test above I used this class
class Main
{
 public static void main (String[] args)
 {
  JavaHit <String, Integer> obj =
   new JavaHit<String, Integer>("TestForString", 37);

  obj.print();
 }
}

Output
TestForString
37

Generics Functions:
In nutshell, you can pass here, different types of arguments. Let see code below.

// Generic functions

class Test
{
 
 static <T> void genericParameterDisplay (T typeofelement)
 {
  System.out.println(typeofelement.getClass().getName() +
      " = " + typeofelement);
 }
 
 public static void main(String[] args)
 {
  // Calling generic method for Integer
  genericParameterDisplay(37);

  // Calling generic method for String
  genericParameterDisplay("TestForString");

  // Calling generic method for double
  genericParameterDisplay(10.02);
 }
}

Output:
37
TestForString
10.02

Generics Advantages :

1. Code Reuse.
2. Type safety
3. No need Type casting

No comments:

Post a Comment