Thursday, August 1, 2013

Java class with generic type

Generic type T specifies the type of the object that will be handled in a class.
The advantage of using generic type is the object type is checked in compile time. A class that is designed to handle object with type A will not be mistakenly passed an object with Type B

Suppose we define a Container to store and retrieve an object. In order to know what type of object we will put later, we add type parameter T.
public interface Container<T> {
 public void set(T t);
 public T get();
}

and we have fruits Apple and Orange that will be put the in container
public class Apple {

 private String label;

 public Apple(String label) {
  super();
  this.label = label;
 }
 
 @Override
 public String toString() {
  return "Apple [label=" + label + "]";
 }

}

public class Orange {

 private String label;

 public Orange(String label) {
  super();
  this.label = label;
 }

 @Override
 public String toString() {
  return "Orange [label=" + label + "]";
 }

}

A box that implements Container will be used to put Apple or Orange
public class Box implements Container<T> {

 private T t;
 
 public void set(T t) {
  this.t = t;
 }
 public T get() {
  return t;
 }

}

To create a box that can have Apple only
Box<Apple> genericAppleBox = new Box<Apple>();

A box that can have Orange only
Box<Orange> genericOrangeBox = new Box<Orange>();

If we try to put an Orange in the apple box,
genericAppleBox.set(orange);

the compiler will complain, "The method set(Apple) in the type Box is not applicable for the arguments (Orange)"

The type parameter also can be specified in the class definition
To declare a box class that will store Apple only
public class AppleBox implements Container<Apple> {

 private Apple apple;

 public Apple get() {
  return apple;
 }

 public void set(Apple apple) {
  this.apple = apple;
 }
 
}

A box will will store Orange only
public class OrangeBox implements Container<Orange> {

 private Orange orange;

 public Orange get() {
  return orange;
 }

 public void set(Orange orange) {
  this.orange = orange;
 }

}

To create the box for Apple only
AppleBox specificAppleBox = new AppleBox();

To create the box for Orange only
OrangeBox specificOrangeBox = new OrangeBox();

If we try to put an Orange to the Apple box,
specificAppleBox.set(orange);

the compiler will complain, "The method set(Apple) in the type AppleBox is not applicable for the arguments (Orange)"

Reference
http://docs.oracle.com/javase/tutorial/java/generics/