指定上限为T类:表示泛型必须为T类及其子类;
指定上限为T接口:表示泛型必须为T接口及其实现类;
不管是类还是接口,格式都为extends T;
指定下限为T类:表示泛型必须为T类及其父类;
指定上限为T接口:表示泛型必须为T接口及其父接口;
不管是类还是接口,格式都为? super T;
不能只设置下限,设置下限的同时必须设置上限(参数例外);
- interface Inf1<T> {
- }
- interface Inf2 {
- }
- class A<T> {
- }
- class B<T> extends A<T> implements Inf1{
- }
- class C<T> extends B<T> {
- }
- class D extends C {
- }
interface Inf1<T> {
}
interface Inf2 {
}
class A<T> {
}
class B<T> extends A<T> implements Inf1{
}
class C<T> extends B<T> {
}
class D extends C {
}
例:
泛型T上限为B
- class Dog<T extends B> {
- private T t;
- private void fun1() {
- /**T的类型为B*/
- Dog dog = new Dog();
- }
- private void fun2() {
- /**T的类型为B*/
- Dog<B> dog = new Dog<B>();
- }
- private void fun3() {
- /**T的上限为B,即T只能是T及其子类所以下面代码是错的*/
- Dog<A> dog = new Dog<A>();
- }
- }
class Dog<T extends B> {
private T t;
private void fun1() {
/**T的类型为B*/
Dog dog = new Dog();
}
private void fun2() {
/**T的类型为B*/
Dog<B> dog = new Dog<B>();
}
private void fun3() {
/**T的上限为B,即T只能是T及其子类所以下面代码是错的*/
Dog<A> dog = new Dog<A>();
}
}
二、类的上下限
例:
T的上限为A,下限为C
- class Cat<T extends A<? super C>> {
- private T t;
- private void fun1() {
- Cat<A<? super C>> cat1 = new Cat<A<? super C>>();
- cat1.t = new A();
- cat1.t = new B();
- cat1.t = new C();
- }
- }
class Cat<T extends A<? super C>> {
private T t;
private void fun1() {
Cat<A<? super C>> cat1 = new Cat<A<? super C>>();
cat1.t = new A();
cat1.t = new B();
cat1.t = new C();
}
}
三、方法上限下,与类的上下限设置一样
例:
- class Point<T,K,V> {
- }
- class Test {
- /**强制要求show1参数Point对象被创建时,指定泛型
- * T上限为A;
- * K上限为Inf1;
- * V下限为B;
- * */
- public void show1(Point<? extends A, ? extends Inf1, ? super B> p) {
- }
- /**
- * T为B符合T上限为A; 因为B继承A类
- * K为B符合K上限为Inf1;因为B实现了Inf1
- * V为A符合V下限为B; 因为 A是B的父类
- */
- private void fun() {
- Point<B, B, A> point = new Point<B,B,A>();
- this.show1(point);
- }
- }