In this tutorial, we will learn about the Java Generics with the help of an example.
In Java, Generics helps to create classes, interfaces, and methods that can be used with different types of objects (data). Hence, allows us to reuse our code. Note: Generics does not work with primitive types (int, float, char, etc).
You can write a single generic method declaration that can be called with arguments of different types.Following are the rules to define Generic Methods :
class Codemistic {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
demo.genericsMethod("Java Programming");
}
}
class DemoClass {
// generics method
public void genericsMethod(T data) {
System.out.println("This is a generics method.");
System.out.println("The data passed to method is " + data);
}
}
Output:
This is a generics method.
The data passed to the method: Java Programming
A class that can refer to any type is known as a generic class. Here, we are using the T type parameter to create the generic class of specific type. Let's see a simple example to create and use the generic class.
class MyGen<T>
{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
//The T type indicates that it can refer to any type (like String, Integer, and Employee).
//The type you specify for the class will be used to store and retrieve the data.
class TestGenerics3
{
public static void main(String args[])
{
MyGen m=new MyGen();
m.add(2);
System.out.println(m.get());
}
}
Output
2
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound. Example:
class GenericsClass <T extends Number>
{
public void display()
{
System.out.println("This is a bounded type generics class.");
}
}
class Main
{
public static void main(String[] args)
{
// create an object of GenericsClass
GenericsClass obj = new GenericsClass<>();
}
}
This means T can only work with data types that are children of Number (Integer, Double, and so on). However, we have created an object of the generics class with String. This is why when we run the program, we will get the following error.
GenericsClass<String> obj = new GenericsClass<>();
^
reason: inference variable T has incompatible bounds
equality constraints: String
lower bounds: Number
where T is a type-variable:
T extends Number declared in class GenericsClass