java泛型——上下限

来源:互联网 发布:淘宝商品详情页设计 编辑:程序博客网 时间:2024/05/16 08:57

 指定上限为T类:表示泛型必须为T类及其子类;
 指定上限为T接口:表示泛型必须为T接口及其实现类;
 不管是类还是接口,格式都为extends T;
 指定下限为T类:表示泛型必须为T类及其父类;
 指定上限为T接口:表示泛型必须为T接口及其父接口;
 不管是类还是接口,格式都为? super T;
 不能只设置下限,设置下限的同时必须设置上限(参数例外);


[html] view plaincopyprint?
  1. interface Inf1<T> {  
  2.       
  3. }  
  4. interface Inf2 {  
  5.       
  6. }  
  7. class A<T> {  
  8.       
  9. }  
  10. class  B<T> extends A<T> implements Inf1{  
  11.       
  12. }  
  13.    
  14. class C<T> extends B<T> {  
  15.       
  16. }  
  17.    
  18. class D extends C {  
  19.       
  20. }  


一、类的上限
 例:

泛型T上限为B

[html] view plaincopyprint?
  1. class Dog<T extends B> {  
  2.     private T t;  
  3.     private void fun1() {  
  4.         /**T的类型为B*/  
  5.         Dog dog = new Dog();  
  6.     }  
  7.     private void fun2() {  
  8.         /**T的类型为B*/  
  9.         Dog<B> dog = new Dog<B>();  
  10.     }  
  11.     private void fun3() {  
  12.         /**T的上限为B,即T只能是T及其子类所以下面代码是错的*/  
  13.         Dog<A> dog = new Dog<A>();  
  14.     }  
  15. }  

二、类的上下限
例:

T的上限为A,下限为C

[html] view plaincopyprint?
  1. class Cat<T extends A<? super C>> {  
  2.     private T t;  
  3.     private void fun1() {  
  4.          Cat<A<? super C>> cat1 = new Cat<A<? super C>>();  
  5.          cat1.t = new A();  
  6.          cat1.t = new B();  
  7.          cat1.t = new C();  
  8.     }  
  9. }  

三、方法上限下,与类的上下限设置一样

例:

[html] view plaincopyprint?
  1. class Point<T,K,V> {  
  2.       
  3. }  
  4. class Test {  
  5.     /**强制要求show1参数Point对象被创建时,指定泛型  
  6.      * T上限为A;  
  7.      * K上限为Inf1;  
  8.      * V下限为B;  
  9.      * */  
  10.     public void show1(Point<? extends A, ? extends Inf1, ? super B> p) {   
  11.     }  
  12.     /**  
  13.      * T为B符合T上限为A; 因为B继承A类  
  14.      * K为B符合K上限为Inf1;因为B实现了Inf1  
  15.      * V为A符合V下限为B; 因为 A是B的父类  
  16.      */  
  17.     private void fun() {  
  18.         Point<B, B, A> point = new Point<B,B,A>();  
  19.         this.show1(point);  
  20.     }  
  21. }  
1 0
原创粉丝点击