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.
Example
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.
/* * Generic class with parameter T * Writen by: Kindson The Genuis */ public class Box<T> { private T t; //Instance variable of type T public Box(T t) //Generic constructor take type T { this.t = t; } public T get() //Generic method get, returns type T { return t; } }
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.
/* * Creating and calling methods of a generic class * Writen by: Kindson The Genuis */ public class TestGeneric { public static void main(String[] args) { // TODO Auto-generated method stub Box<Integer> intBox = new Box<Integer>(20); Box<String> strBox = new Box<String>("Generic Tutorial!"); Box<Character> charBox = new Box<Character>('K'); Box<Float> floBox = new Box<Float>(45.04f); System.out.println("Integer value: " + intBox.get()); System.out.println("String value: " + strBox.get()); System.out.println("Character value: " + charBox.get()); System.out.println("Float value: " + floBox.get()); } }
Listing 1.1: Using a generic class
If you are using Eclipse IDE, then your output would be like shown in Figure 1.0
