View RSS Feed

Advanced Java

Generic Methods and Constructors

Rate this Entry
by , 02-18-2012 at 03:37 PM (1207 Views)
Within methods declaration of the type parameters could be done and constructor signatures for creation of the generic constructors or generic methods.
Java Code: This is the code to explain Generic Methods
public class Box<T> {

    private T t;          

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

    public T get() {
        return t;
    }

    public <U> void inspect(U u){
        System.out.println("T: " +
            t.getClass().getName());
        System.out.println("U: " +
            u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = 
            new Box<Integer>();
        integerBox.add(new Integer(10));
        integerBox.inspect("some text");
    }
}
The output from this program is:

Java Code: Output of above program
T: java.lang.Integer
U: java.lang.String

Submit "Generic Methods and Constructors" to Facebook Submit "Generic Methods and Constructors" to Digg Submit "Generic Methods and Constructors" to del.icio.us Submit "Generic Methods and Constructors" to StumbleUpon Submit "Generic Methods and Constructors" to Google

Comments