Thursday, 2 June 2011

Generics


Generics add stability to your code by making more of your bugs detectable at compile time. Some programmers choose to learn generics by studying the Java Collections Framework; after all, generics are heavily used by those classes.

For class Box:

In the following example T can be used like the regular types.
For e.g. T temp, T t, etc, etc…

At a later stage we need to replace T with other data objects such as                 Integer, String etc, when we create objects of class Box…

For class BoxDemo:

Box<Integer> integerBox=new Box<Integer>();//<Integer> replaces every instance of T in the Box class with Integer…
i.e. every T=integer

Once integerBox is initialized, we're free to invoke its get method without providing a cast…

Hence, if we use integerBox.add(“string”) to add a string, it reports a compile time error…

/**
 * Generic version of the Box class.
 */
public class Box<T> {

    private T t; // T stands for "Type"         

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

public class BoxDemo {
 
        public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.add(new Integer(10));
        Integer someInteger = integerBox.get(); // no cast!
        System.out.println(someInteger);
    }
}

No comments:

Post a Comment