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