Generics in Java

Generics are a function of Java that allows programmers to specify the type of data they want to work with in a class, interface, or method. In this tutorial, let’s learn more about generics in Java.

Why need generics?

Before generics is introduced, we only work with classes, interfaces or methods with a fixed data type.

For example, we declare a List object as follows:

With the above declaration, assume that we want to work only with the String object. But because l variable is a Collection of Object objects, so we can use it with any type of data. The following declaration will be valid:

This will entangle the type of data we want to work on, and sometimes we do not have control over the compile time.

That is the reason for the need for generics in Java. With generics, we will specify the type of data we will work on at compile time.

The above example can be rewritten as follows:

Then, the following statement will report the error immediately:

How to create a class generics in Java

First, let’s define a non-generics class first and then convert this class to the generics class.

The content of the non-generics class is as follows:

With this definition, the obj attribute of the Student object and the obj parameter in the set() method could be any object. And if the two objects are different, an exception will occur.

To fix the data type for the obj attribute, and in the set() method, we will apply generics in Java. As follows:

Uses generics class

To use generics class, when initializing an object, we will pass the type of data we want to that object.

For the Student example above, we can initialize the Student object with the String data type as follows:

At this point, we cannot use the set() method with other String data types, for example:

Generics in Java

Add Comment