每当您要将类型参数限制为特定类的子类型时,都可以使用有界类型参数。如果仅将类型(类)指定为有界参数,则当前泛型类仅接受该特定类的子类型。
您可以通过在角括号内将类型扩展为所需的类来声明绑定参数-class Sample
示例
在下面的Java示例中,泛型类Sample将类型参数限制为使用有界参数的Number类的子类。class Sample {
T data;
Sample(T data){
this.data = data;
}
public void display() {
System.out.println("Data value is: "+this.data);
}
}
public class BoundsExample {
public static void main(String args[]) {
Sample obj1 = new Sample(20);
obj1.display();
Sample obj2 = new Sample(20.22d);
obj2.display();
Sample obj3 = new Sample(125.332f);
obj3.display();
}
}
输出结果Data value is: 20
Data value is: 20.22
Data value is: 125.332
现在,如果将其他类型作为参数传递给此类(例如,String),则将生成编译时错误。
示例public class BoundsExample {
public static void main(String args[]) {
Sample obj1 = new Sample(20);
obj1.display();
Sample obj2 = new Sample(20.22d);
obj2.display();
Sample obj3 = new Sample("Krishna");
obj3.display();
}
}
编译时错误BoundsExample.java:16: error: type argument String is not within bounds of type-variable T
Sample obj3 = new Sample("Krishna");
^
where T is a type-variable:
T extends Number declared in class Sample
BoundsExample.java:16: error: type argument String is not within bounds of type-variable T
Sample obj3 = new Sample("Krishna");
^
where T is a type-variable:
T extends Number declared in class Sample
2 errors
多重界限
您还可以使用extend关键字将多个类型作为有界参数列出,并使用“&”将它们分隔开。传递给此类的(type)参数应该是所有指定类的子类型。
示例
在下面的示例中,我们设置了上限的Number和Comparable类型,即该类接受属于这两个类的子类的类型。class Sample >{
T data;
Sample(T data){
this.data = data;
}
public void display() {
System.out.println("Data value is: "+this.data);
}
}
public class BoundsExample {
public static void main(String args[]) {
Sample obj1 = new Sample(22);
obj1.display();
Sample obj2 = new Sample(20.22d);
obj2.display();
}
}
输出结果Data value is: 22
Data value is: 20.22
如果将AtomicInteger类作为参数传递给Sample类,因为它不是可比较类的子类型,则将生成编译时错误
示例import java.util.concurrent.atomic.AtomicInteger;
class Sample >{
T data;
Sample(T data){
this.data = data;
}
public void display() {
System.out.println("Data value is: "+this.data);
}
}
public class BoundsExample {
public static void main(String args[]) {
Sample obj1 = new Sample(22);
obj1.display();
Sample obj2 = new Sample(20.22d);
obj2.display();
Sample obj3 = new Sample(124);
obj3.display();
}
}
编译时错误BoundsExample.java:16: error: type argument String is not within bounds of type-variable T
Sample obj3 = new Sample("Krishna");
^
where T is a type-variable:
T extends Number declared in class Sample
BoundsExample.java:16: error: type argument String is not within bounds of type-variable T
Sample obj3 = new Sample("Krishna");
^
where T is a type-variable:
T extends Number declared in class Sample
2 errors