# Is it mandatory to use T for type-parameter, while defining Generics classes/methods in Java?

Java 8Object Oriented ProgrammingProgramming

Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.

To define a generic class you need to specify the type parameter you are using in the angle brackets “<>” after the class name and you can treat this as datatype of the instance variable an proceed with the code.

Example − Generic class

class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}

Usage − While instantiating the generic class you need to specify the object name after the class within the angular brackets. Thus, chose the type of the type parameter dynamically and pass the required object as a parameter.

public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}

Example generic methods

Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method.

While defining generic methods you need to specify the type parameter in the angular brackets and use it as a local variable.

## Example

Live Demo

public class GenericMethod {
<T>void sampleMethod(T[] array) {
for(int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
}
public static void main(String args[]) {
GenericMethod obj = new GenericMethod();
Integer intArray[] = {45, 26, 89, 96};
obj.sampleMethod(intArray);
String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
obj.sampleMethod(stringArray);
}
}

## Output

45
26
89
96
Krishna
Raju
Seema
Geeta

## Is <T> mandatory

To specify the generic parameter type we use T within angle brackets. Yes, it is mandatory to specify it. If you remove it and its usage in generic classes and methods they will become normal classes and methods.

Published on 09-Sep-2019 08:26:15