好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java有界类型参数的实例用法

java有界类型参数的使用

1、为了声明一个有界类型参数,列出类型参数的名称,然后是extends关键字,最后是它的上界。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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());

     }

 

     public static void main(String[] args) {

         Box<Integer> integerBox = new Box<Integer>();

         integerBox.set( new Integer( 10 ));

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

     }

}

2、通过修改泛型方法包含这个有界类型参数。由于我们在调用inspect时还使用了String,因此编译将失败

?

1

2

3

4

5

Box.java: 21 : <U>inspect(U) in Box<java.lang.Integer> cannot

   be applied to (java.lang.String)

                         integerBox.inspect( "10" );

                                   ^

1 error

3、除对可用于实例化泛型类型的类型进行限制外,还允许调用在边界中定义的方法。

?

1

2

3

4

5

6

7

8

9

10

11

12

public class NaturalNumber<T extends Integer> {

 

   private T n;

 

   public NaturalNumber(T n)  { this .n = n; }

 

   public boolean isEven() {

     return **n.intValue()** % 2 == 0 ;

   }

 

   // ...

}

知识点扩展:

当我们希望对泛型的类型参数的类型进行限制的时候(好拗口), 我们就应该使用有界类型参数(Bounded Type Parameters). 有界类型参数使用extends关键字后面接上边界类型来表示, 注意: 这里虽然用的是extends关键字, 却不仅限于继承了父类E的子类, 也可以代指显现了接口E的类. 仍以Box类为例:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

public class Box<T> {

 

     private T obj;

 

     public Box() {}

 

     public T getObj() {

         return obj;

     }

 

     public void setObj(T obj) {

         this .obj = obj;

     }

 

     public Box(T obj) {

         super ();

         this .obj = obj;

     }

 

     public <Q extends Number> void inspect(Q q) {

         System.out.println(obj.getClass().getName());

         System.out.println(q.getClass().getName());

     }

}

我加入了public <Q extends Number> void inspect(Q q){...}方法, 该方法的泛型只能是Number的子类.

?

1

2

3

4

5

Box<String> b = new Box<>();

b.setObj( "Hello" );

b.inspect( 12 );

b.inspect( 1.5 );

// b.inspect(true); // 编译出错

到此这篇关于java有界类型参数的使用的文章就介绍到这了,更多相关java有界类型参数的使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestpy.cn/java/jichu/31865.html

查看更多关于java有界类型参数的实例用法的详细内容...

  阅读:16次