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] |
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.javapublic 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");
}
}
OutputT: 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:
No comments:
Post a Comment