Articles

What is Generics in Java with Example ?

Share

Generic programming is a way of creating classes, interfaces, and methods to work with various data types. It provides the flexibility to write a feature that is independent of any specific datatype.

In simple words, it allows us to create a class, interface, or method that accepts various datatypes automatically in the parameterized way. Therefore, Generics concept is also termed as parameterized type.

In Java, the Generics concept is one of the crucial features and introduced in JDK 5.

After Generics addition, Java becomes a Type Safety Language. As we know, Object class is the root class of all other classes, and therefore, reference from any type is acceptable which leads to a lack of type safety.

Type Safety ensures prevention from uncertain behavior of a program by verifying a variable holding a value as per its datatype in order to avoid type errors while compilation.

Java Generics is similar to C++’s Standard Template Library (STL) but both languages follow different approaches.

The major impact of Generics concept can be seen in the collection framework particularly.A collection framework offers various classes (such as ArrayList ,LinkedList, HashMap) and interfaces (such as List,Map). It deals with a group of objects and was not type safe before Generics were introduced. After addition of generics, the collection becomes type safe as they start accepting type parameter in form of argument , for example List<Integer> listObj = new ArrayList<>() .

Why we use Generics in Java :

  • It gradually improves code usability
  • It ensures type safety
  • It resolves the type casting problem
  • It enables us to write a generic algorithm that works with datatypes independently

How to Create a Generic Class in Java ?

When a class accepts type parameter within an angular notation, it is considered as a generic type ,in other words, parameterized type.

Syntax:

class Test<T>{

}

T stands for Type Parameter.

Some Important points related to Generics

  • Generic cannot be used with primitive type, it only works with a reference type.
  • Polymorphism doesn’t apply on Type Parameter, i.e ArrayList<Object> obj = new ArrayList<String>(); // would throw compile time error
  • One generic type reference can’t be assigned to another generic type reference.
  • Generic concept is applicable at compile time, but no such concept is there for runtime.
public class GenericClassExample<T> {
    T instanceVariable;

    public T getInstanceVariable() {
        return instanceVariable;
    }

    public void setInstanceVariable(T instanceVariable) {
        this.instanceVariable = instanceVariable;
    }

    public static void main(String[] args) {
        GenericClassExample<String> stringObj = new GenericClassExample<>();
        stringObj.setInstanceVariable("I am String Type !");
        System.out.println("Printing String Type :" + stringObj.getInstanceVariable());

        GenericClassExample<Integer> integerObj = new GenericClassExample<>();
        integerObj.setInstanceVariable(4);
        System.out.println("Printing Integer Type :" + integerObj.getInstanceVariable());
    }
}

Output :

Printing String Type :I am String Type !
Printing Integer Type :4

How to Create Generic Method in Java ?

It is possible to create a generic method with generic and non generic classes.

Syntax :

<Type parameter > returnType methodName(params);
public class GenericMethodExample {

    public <T> void printValues(T value) {
        System.out.println("Value : " + value);
    }

    public static void main(String[] args) {
        GenericMethodExample obj = new GenericMethodExample();
        obj.printValues(43);
        obj.printValues("ProgrammerBay");
        obj.printValues(54.43);
    }
}

Output:

Value : 43
Value : ProgrammerBay
Value : 54.43

Bounded Type Parameter

It allows us to limit the object type that can be passed through type parameter by using extends clause.

Syntax :

<T extends className or interfaceName>

Now, the class and its subclasses, or in case of interface, interface and its implementing classes, can be replaced with Type parameter. For instance, suppose type parameter extends Number class, then only the Number class object itself or those classes that extends it can be substituted with T, such as Integer, Short, Double and more.

Java Program to show the working of Bounded Type Parameter

public class Main <T extends Number>
{
    private void print(T x){
        System.out.println("Number : "+x);
    }
    
  public static void main(String[] args) {
    Main<Integer> integerObj = new Main<>();
    integerObj.print(10);
  }
}

Output :

Number : 10

Passing String Type Parameter would through :

Main<String> StringObj = new Main<>();
  integerObj.print("Num");
 error : type argument String is not within bounds of type-variable T

This post was last modified on March 21, 2021

Sandeep Verma

Published by
Sandeep Verma
Tags: Bounded type Parameter Generic Class generic concept in Java Generic Programming in Java java What is Generic Programming