Thursday, 8 June 2017

Java Tutorial: Java Generics[Define a generic method which accepts Type parameter with single bound] ~ foundjava


Click here to watch in Youtube :
https://www.youtube.com/watch?v=ptvG7KBgTp8&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Java Generics[Define a generic method which accepts Type parameter with single bound] 
Box.java
public class Box<T>
{

    private T t;

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

    public T get()
    {
        return t;
    }

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

}
GenericDemo.java
public class GenericDemo
{

    public static void main(String[] args)
    {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(100));
        integerBox.inspect(new Integer(200));
        System.out.println("-------------------");
        integerBox.inspect(new Double(20.23));
        System.out.println("-------------------");
        integerBox.inspect(new Long(2000));

        /*
         * error: this is still String!
         */
        //integerBox.inspect("some text");

    }

}
Output
T: java.lang.Integer
U: java.lang.Integer
-------------------
T: java.lang.Integer
U: java.lang.Double
-------------------
T: java.lang.Integer
U: java.lang.Long
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment