Other Java Topics
- Interfaces in Java
- Threading and Multithreading in Java
- Introduction to Generics in Java
- Bounded Generics in Java
- Generic Classes in Java
Today we are going to be looking at generic classes in Java. This is continuation of our Tutorials on Generics in Java.
We can also create generic classes in Java. In this case, the type of object that can be instantiated with this class is not known at design time. The return type is specified at run time.
A generic class declaration in Java is similar to normal classes with the exception that the the generic class name is followed by a type parameter section. The type parameter section can have one or more type parameters which are separated by commas.
Classes created in this way are known as parameterized classes and can accept one or more parameters.
In this example, we define a generic class. Then we create objects based on the generic class and call the methods of the generic class.
Listing 1.0: Class definition of a generic class
The class definition of a generic class is presented in Listing 1.0. In this code, we can see that this class has a constructor that take a parameter of type T which would be specified when the object is created.
Example: Using a Generic Class
Copy the code below to your IDE and run it and view the output.
Listing 1.1: Using a generic class
If you are using Eclipse IDE, then your output would be like shown in Figure 1.0