Generics


Generics

Generics mean parameterized types. The idea is to allow type (Integer, String etc, and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
An entity such as class, interface, or method that operates on a parameterized type is called a generic entity.
// To create an instance of generic class
BaseType < Type > obj = new BaseType < Type >()
When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char or double.

Advantage of Java Generics
  • Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other objects.
  • Type casting is not required: There is no need to typecast the object.
  • Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

Generics Examples

Generics for single type parameter

// We use < > to specify Parameter type
class Test < T >{
// An object of type T is declared
T obj;
Test(T obj){
this.obj = obj;
} // constructor

public T getObject() {
return this.obj;
}
}

// Driver class to test above
class Main{

public static void main (String[] args){
// instance of Integer type
Test <Integer > iObj = new Test<Integer >(15);
System.out.println(iObj.getObject());

// instance of String type
Test <String> sObj = new Test<String>("Hello");
System.out.println(sObj.getObject());
}
}

Generics for multiple type parameter

// A Simple Java program to show multiple type parameters in Java Generics

// We use <> to specify Parameter type
class Test <T, U>{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(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);
}
}

// Driver class to test above
class Main{
public static void main (String[] args){
Test < String, Integer> obj = new Test <String, Integer >("Hello", 15);
obj.print();
}
}

Object (Unsafe type)

The Object is the superclass of all other classes and Object reference can refer to any type object. These features lack type safety.
public class Object