Generics in Java

Lochana Edirisinghe
2 min readApr 12, 2020

Hello everyone,

Today I will be going to explain about Generics concept in Java programming language. Guys this is a awesome mechanism for type safety since Java JDK 1.5.

This mechanism only works in compile time. Simply, we can understand this concept using the example in below,

I just create a Hospital class,

class Hospital{
public void details(Object obj){
System.out.println(obj);
}
}

class Doctor{
private String id;
private int salary;

public Doctor(String name, int salary) {
this.id = name;
this.salary = salary;
}
@Override
public String toString() {
return "Doctor : "+id+'\n'+"Salary : "+salary ;
}
}

class Teacher{
private String id;
private int salary;

public Teacher(String name, int salary) {
this.id = name;
this.salary = salary;
}
@Override
public String toString() {
return "Teacher : "+id+'\n'+"Salary : "+salary;
}
}

public class Demo {
public static void main(String[] args) {
Hospital hospital= new Hospital();
hospital.details(new Doctor("D001", 100000));
hospital.details(new Teacher("T001", 60000));

}
}

The above code we can insert both Doctor and Teacher objects into Hospital class, because the hospital class takes objects in type of Object class. So we can put any object type into the details method.

But in this case there is no type safety. Then what we can do is, we can use a parameter instead of Object reference(like T) in the Hospital class. Then when we are making Hospital object, we should pass the type of object which we want to send. Then that object type can only be added to the Hospital class.

Let’s we modify the above class,

We can modify Hospital class as follows,

class Hospital<T>{

public void details(T obj){
System.out.println(obj);
}
}

So now when we are going to make a Hospital object, we should pass the parameter type that we need.

If we don’t pass any object type to T , then it takes Object type by default.

public class Demo {
public static void main(String[] args) {
Hospital <Doctor> hospital= new Hospital();
jhospital.details(new Doctor("D001", 100000));
hospital.details(new Teacher("T001", 60000)); (Compile Error)
}
}

Here , hospital.details(new Teacher(“T001”, 60000)); line has compile error. Because the object type that have been passed to Hospital object is Doctor (<Doctor>).

Usually Generics are used in Java Collection classes. Also we can used generics in method overloading. I hope you got some idea about the Generics concept in Java. We will discuss about more details in near future.

Thank you!!

--

--