一般来说泛型编程中只要指定泛型的名字就可以了,但是如果我们想对泛型中的参数进行限制,怎么办?
比如一个泛型class A<E>,其中E是没有限制的,如果相对E限制其必须是String的子类。
这时候要使用有界类型参数(Bounded Type Parameter),语法如下
<T 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<T 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<C> bec = new Bound<C>(new C());
bec.doRunTest();
// Creating object of sub class B and
// passing it to Bound as a type parameter.
Bound<B> beb = new Bound<B>(new B());
beb.doRunTest();
// similarly passing super class A
Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
}
}
输出如下
Inside sub class C
Inside sub class B
Inside super class A
如果实例化时不是extends于A,则会编译报错
Bound<String> bes = new Bound<String>(new String());
error: type argument String is not within bounds of type-variable T
还存在Multiple Bounds使用方式
<T extends superClassName & Interface>
例如
class Bound<T 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.
Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
}
}
输出
Inside super class A