.k=k;
}
public V getK(){
return this.k;
}
public static void main(String[] args)
{
TestGen2<String,Integer> t2=new TestGen2<String,Integer>();
t2.setK(new String(“String”));
t2.setV(new Integer(123));
System.out.println(t2.getK());
System.out.println(t2.getV());
=
=
上边K的范围是<=String ,V的范围是<=Number,注意是“<=”,对于K可以是String的,V当然也可以是Number,也可以是Integer,Float,Double,Byte等。看看下图也许能直观些请看上图A是上图类中的基类,A1,A2分别是A的子类,A2有2个子类分别是A2_1,A2_2。
然后我们定义一个受限的泛型类class MyGen<E extends A2>,这个泛型的范围就是上图中兰色部分。
这个是单一的限制,你也可以对型别多重限制,如下:
class C<T extends Comparable< super T> & Serializable>
我们来分析以下这句,T extends Comparable这个是对上限的限制,Comparable< super T>这个是下限的限制,Serializable是第2个上限。一个指定的类型参数可以具有一个或多个上限。具有多重限制的类型参数可以用于访问它的每个限制的方法和域。
2.4. 多态方法
//Code list 9
class TestGen {
<T extends Object> public static List<T> make(T first) {
return new List<T>(first);