Generic Class in Java

24 Oct, 2020
Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means parameterized types. Using generics, the idea is to allow any data type to be it Integer, String, or any user-defined Datatype and it is possible to create classes that work with different data types.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
Example: Single type parameter
class Solution<T>
{
   T data;
   public static T getData(){
       return data;
   }
}

Example: Multiple type parameters
public class Pair<K, V> {

    private K key;
    private V value;

    public Pair(K key, V value) {
    this.key = key;
    this.value = value;
    }

    public K getKey()    { return key; }
    public V getValue() { return value; }
}

Here in this example, we can use the object or instance of this class as many times with different Parameters as T type. If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas. 
We can write a single generic method declaration that can be called with arguments of different types. Based on the types of arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods 
All generic method declarations have a type parameter section indicated by angle brackets <> that precedes the method’s return type.
Each type parameter section can contain one or more type parameters separated by commas. A type parameter or a type variable is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type which is known as actual type arguments.
A generic method’s body is declared like that of any non-generic method. The point to be noted is that type parameter can represent only reference types, and not primitive types (like int, double, and char).
1.  Type-Safety: One can hold only a single type of objects in generics.     
2.  Type Casting Is Not Required: There is no need to typecast.
Example:
Before Generics 
     List l= new ArrayList();
     l.add("India");
     String s = (String) list.get(0);     // typecasting  
                                          
After Generics, typecasting of the object is not required 
      List<String> l = new ArrayList<String>();    
      l.add("hello");    
      String s = list.get(0);   

3.  Compile -Time Checking: It checks all the errors of datatype related to generics at the time of compile-time so the issue will not occur at the time of runtime.
List<String> list = new ArrayList<String>();    
list.add("hello");    
list.add(32);   //Compile Time Error   

For an instance of Generic class
BaseType <Type> object = new BaseType <Type>();

Note: In parameter Type, we cannot use primitives like int, char, float, etc.
Example:
Java
// Java program to show the// instance of a generic class  // Generic Classes  // we use <> to specify parameter// type and we can add any datatype// like Integer, Double, String,// Character or any user defined// Datatype  // Every time when we need to make an// object of another datatype of this// generic class , we need not to make// the whole class of that datatype again// instead we can simply change the// parameter/Datatype in braces <>  public class Area<T> {      // T is the Datatype like String,    // Integer of which Parameter type,    // the class Area is of    private T t;      public void add(T t)    {        // this.t specify the t variable inside        // the Area Class whereas the right hand        // side t simply specify the value as the        // parameter of the function add()        this.t = t;    }      public T get() { return t; }      public void getArea() {}      public static void main(String[] args)    {        // Object of generic class Area with parameter Type        // as Integer        Area<Integer> rectangle = new Area<Integer>();        // Object of generic class Area with parameter Type        // as Double        Area<Double> circle = new Area<Double>();        rectangle.add(10);        circle.add(2.5);        System.out.println(rectangle.get());        System.out.println(circle.get());    }}
10
2.5


 
Java-Generics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java