Java - Generics Java Generics

What Are Generics?

Java Generics can write polymorphic code that works with any type.


To specify the parameter name in angle brackets < > after the name of the type. You will use T as the parameter name.

class Wrapper<T> {

To use more than one parameter for a type, separate them by a comma.

The following declaration for MyClass takes four parameters named T, U, V, and W:

class MyClass<T, U, V, W> {

T means any type for you, which will be known when you use this class.

Using a Type Parameter to Define a Generic Class

class Wrapper<T> {
        private T ref;

        public Wrapper(T ref) {
                this.ref = ref;

        public T get() {
                return ref;

        public void set(T a) {
                this.ref = a;

To store a String reference in the Wrapper object, you would create it as follows:

Wrapper<String> greetingWrapper = new Wrapper<String>("Hello");

set() and get() method now will work only with String types.

greetingWrapper.set("Hi"); // OK to pass a String
String greeting = greetingWrapper.get(); // No need to cast

A compile-time error. You can use greetingWrapper only to store a String.

greetingWrapper.set(new Integer(101));

To use the Wrapper class to store an Integer, your code will be as follows:

Wrapper<Integer> idWrapper = new Wrapper<Integer>(new Integer(101));
idWrapper.set(new Integer(897)); // OK to pass an Integer
Integer id = idWrapper.get();

// A compile-time error. You can use idWrapper only wth an Integer.

To store a Person object in Wrapper as follows:

Wrapper<Person> personWrapper = new Wrapper<Person>(new Person(1, "Tom"));
personWrapper.set(new Person(2, "May"));
Person laynie = personWrapper.get();


The parameter specified in the type declaration is called a formal type parameter.

T is a formal type parameter in the Wrapper<T> class declaration.

When replacing the formal type parameter with the actual type, it is called a parameterized type.

A reference type in Java, which accepts one or more type parameters, is called a generic type.

Related Topics