Enjoying this Java & Spring tutorial?
Subscribe to Ram N Java on YouTubeIntroduction
Generics in Java enhance type safety by allowing classes, interfaces, and methods to operate on objects of various types while providing compile-time type checking. While standard wrapper classes like Integer and String are commonly used with generics, generic classes can also handle custom user-defined types.
In this tutorial, you will learn how to create a generic class in Java and use it with your own user-defined domain models, eliminating runtime type casting and preventing ClassCastException.
1. Create the User-Defined Class
Create a custom class (such as Employee) representing the domain object you want to store in your generic container:
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [ID=" + id + ", Name=" + name + "]";
}
}
2. Define the Generic Class
Define a generic class named Container<T> that can hold any type specified at instantiation:
public class Container<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
3. Test Generic Class with User-Defined Types
Instantiate the generic class by passing your custom Employee type as the type argument:
public class GenericsDemo {
public static void main(String[] args) {
// Create an instance of Container parameterized with Employee
Container<Employee> empContainer = new Container<>();
Employee emp = new Employee(101, "John Doe");
empContainer.setItem(emp);
// Retrieve the stored object without explicit casting
Employee retrievedEmp = empContainer.getItem();
System.out.println("Stored Item: " + retrievedEmp);
}
}
Watch More Java Tutorials
Click here to watch in Youtube :
https://www.youtube.com/watch?v=88Zfu_d9Dkw&list=UUhwKlOVR041tngjerWxVccw
Bird.java
public class Bird { private String birdName; public String getBirdName() { return birdName; } public void setBirdName(String birdName) { this.birdName = birdName; } }Employee.java
public class Employee { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }GenericFactory.java
/* * It is possible to generify your own Java classes. Generics is not * restricted to the predefined classes in the Java API's. * * The <T> is a type token that signals that this class can have a type set * when instantiated. */ public class GenericFactory<T> { Class<?> theClass = null; public GenericFactory(Class<?> theClass) { this.theClass = theClass; } public T createInstance() throws IllegalAccessException, InstantiationException { return (T) this.theClass.newInstance(); } }GenericDemo.java
public class GenericDemo { public static void main(String[] args) throws IllegalAccessException, InstantiationException { /* * It is not necessary to cast the object returned from the * factory.createInstance() method. The compiler can deduct the type of * the object from the generic type of the GenericFactory created, * because you specified the type inside the <>. */ GenericFactory<Employee> empFactory = new GenericFactory<Employee>(Employee.class); Employee employee = empFactory.createInstance(); System.out.println(employee); GenericFactory<Bird> birdFactory = new GenericFactory<Bird>(Bird.class); Bird bird = birdFactory.createInstance(); System.out.println(bird); } }
Output
Employee@1b701da1 Bird@442d9b6eClick the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsDemo_GenericClass_Bird_Emp_App.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/GenericsDemo_GenericClass_Bird_Emp_App
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/47d09ebb24294f7b507419345f38ec4cde27d544/BasicJava/GenericsDemo_GenericClass_Bird_Emp_App/?at=master
See also: