java 参数子类_我们如何将泛型(类型参数)限制为Java中特定类的子类?

每当您要将类型参数限制为特定类的子类型时,都可以使用有界类型参数。如果仅将类型(类)指定为有界参数,则当前泛型类仅接受该特定类的子类型。

您可以通过在角括号内将类型扩展为所需的类来声明绑定参数-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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值