Java - Class Generic Classes

What is generics?

Using generics, you can write code for various the type of the objects.

Java allows you to create generic classes, constructors, and methods.

Syntax

A generic class is defined using formal type parameters.

Formal type parameters are a list of comma-separated variable names placed in angle-brackets <> after the class name.

The following code declares a class Wrapper that takes one formal type parameter:

public class Wrapper<T>  {
   // Code for the Wrapper class goes here
}

The parameter has a name T.

T is a type variable, which could be any reference type in Java, such as String, Integer, Double, etc.

Primitive types are not allowed as the actual type parameters for a generic class.

The formal type parameter value is specified when the Wrapper class is used.

The classes that take formal type parameter are called parameterized classes.

Usage

To declare a variable of the Wrapper<T> class using the String type as its formal type parameter.

Wrapper<String> stringWrapper;

Java allows you to use a generic class without specifying the formal type parameters for backward compatibility.

Wrapper aRawWrapper;

When a generic class is used without the actual type parameters, it is called raw type.

A class may take more than one formal type parameter.

public class Mapper<T, R>  {
}

You can declare variable of the Mapper<T, R> class as follows:

Mapper<String, Integer> mapper;

Formal Type

The formal type parameters are available inside the class body to be used as types.

class Wrapper<T> {
        private T obj;

        public Wrapper(T obj) {
                this.obj = obj;
        }

        public T get() {
                return obj;
        }

        public void set(T obj) {
                this.obj = obj;
        }
}

You can create an object of the generic type as follows:

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

Or in shorter version.

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

Demo

class Wrapper<T> {
  private T obj;//from w  w  w .j  a v a 2s  . co  m

  public Wrapper(T obj) {
    this.obj = obj;
  }

  public T get() {
    return obj;
  }

  public void set(T obj) {
    this.obj = obj;
  }
}

public class Main {
  public static void main(String[] args) {
    Wrapper<String> w1 = new Wrapper<>("Book2s.com");
    String s1 = w1.get();
    System.out.println("s1=" + s1);

    w1.set("new value");
    String s2 = w1.get();
    System.out.println("s2=" + s2);

    w1.set(null);
    String s3 = w1.get();
    System.out.println("s3=" + s3);
  }
}

Result