一般来说泛型编程中只要指定泛型的名字就可以了,但是如果我们想对泛型中的参数进行限制,怎么办?
比如一个泛型class A
这时候要使用有界类型参数(Bounded Type Parameter),语法如下
extends superClassName>
使用例子
- // This class only accepts type parameters as any class
- // which extends class A or class A itself.
- // Passing any other type will cause compiler time error
-
- class Bound
extends A> - {
-
- private T objRef;
-
- public Bound(T obj){
- this.objRef = obj;
- }
-
- public void doRunTest(){
- this.objRef.displayClass();
- }
- }
-
- class A
- {
- public void displayClass()
- {
- System.out.println("Inside super class A");
- }
- }
-
- class B extends A
- {
- public void displayClass()
- {
- System.out.println("Inside sub class B");
- }
- }
-
- class C extends A
- {
- public void displayClass()
- {
- System.out.println("Inside sub class C");
- }
- }
-
- public class BoundedClass
- {
- public static void main(String a[])
- {
-
- // Creating object of sub class C and
- // passing it to Bound as a type parameter.
- Bound
bec = new Bound(new C()); - bec.doRunTest();
-
- // Creating object of sub class B and
- // passing it to Bound as a type parameter.
- Bound beb = new Bound(new B());
- beb.doRunTest();
-
- // similarly passing super class A
- bea.doRunTest();
-
- }
- }
输出如下
- Inside sub class C
- Inside sub class B
- Inside super class A
如果实例化时不是extends于A,则会编译报错
- Bound
bes = new Bound(new String()); -
- error: type argument String is not within bounds of type-variable T
还存在Multiple Bounds使用方式
extends superClassName & Interface>
例如
- class Bound
extends A & B> - {
-
- private T objRef;
-
- public Bound(T obj){
- this.objRef = obj;
- }
-
- public void doRunTest(){
- this.objRef.displayClass();
- }
- }
-
- interface B
- {
- public void displayClass();
- }
-
- class A implements B
- {
- public void displayClass()
- {
- System.out.println("Inside super class A");
- }
- }
-
- public class BoundedClass
- {
- public static void main(String a[])
- {
- //Creating object of sub class A and
- //passing it to Bound as a type parameter.
- bea.doRunTest();
-
- }
- }
输出
Inside super class A