Java Generics

Profile picture for user arilio666

Java generics is a Java programming language feature that permits the creation of generic classes, interfaces, and methods that can interact with many data types. Generics allow you to construct type-safe reusable code without explicit casting, producing more robust and maintainable code.

Why Generics?

The object is the superclass of all other classes, and an Object reference can refer to any object. These features are not type-safe. Generics include this form of safeguard.

Generic Classes

Generic classes are classes that have one or more type parameters. When a generic class object is formed, the type parameters are supplied, allowing different data types to be utilized with the same class.

public class Cal<Z> {
   private Z item;
   public void setItem(Z item) {
       this.item = item;
   public Z getItem() {
       return item;

Generic Function

We can also build generic functions that, depending on the parameters supplied to the generic method, can be called with different sorts of arguments. The compiler handles each method.

package week1.day2;
public class Calculator {
    static <T> void genericExample(T dis) {
        System.out.println(dis.getClass().getName() + " = " + dis);
    public static void main(String[] args) {
        genericExample("Monkey D Luffy");
  • Here we created a generic method with Argument T.
  • Then we ask it to print the class and name with the specified data type.
  • We called the arguments on three different datatypes.


java.lang.Integer = 11
java.lang.String = Monkey D Luffy
java.lang.Double = 1.0

Benefits Of Generics

  • We can create a method/class/interface once and use it for any type.
  • Generics cause mistakes to emerge at build time rather than run time (it is usually preferable to know about flaws in your code at compile time than to have it fail at run time).