我们在使用泛型的时候,由于泛型擦除的影响(泛型擦除可参考泛型擦除是什么?),泛型参数在未定义边界的情况下,都会被默认擦除为 Object ,从而使得我们无法调用泛型参数内的某个具体方法。如同下例,我们无法在 Plate 类中直接调用泛型参数中的任何具体方法。
public abstract class Fruit {
public abstract void getName();
}
public class Apple extends Fruit {
@Override
public void getName() {
System.out.println("This is an Apple");
}
}
public class Plate<T> {
private T item;
public Plate(T item) {
this.item = item;
}
public void getName() {
//无法被编译
//item.getName();
}
}
但我们为泛型加上边界之后,泛型被擦除的范围就会变成由我们定义的边界,下例中泛型参数被擦除的边界被限制为 Fruit 及 Fruit 的任何子类,于是我们便可调用 Fruit 类中定义的方法。
public class Plate<T extends Fruit> {
private T item;
public Plate(T item) {
this.item = item;
}
public void getName() {
item.getName();
}
public static void main(String[] args) {
Plate<Apple> applePlate = new Plate<>(new Apple());
applePlate.getName();
}
}
This is an Apple
除了定义泛型参数的继承关系外,我们还可以限制泛型参数必须实现某个接口,如果要限制泛型参数满足多个条件可以用 & 进行连接。
public interface ShowCount {
public void showCount();
}
public interface ShowPrice {
void ShowPrice();
}
public class Apple extends Fruit implements ShowCount, ShowPrice {
@Override
public void getName() {
System.out.println("This is an Apple");
}
@Override
public void showCount() {
System.out.println("count is 5");
}
@Override
public void ShowPrice() {
System.out.println("price is 2");
}
}
public class Plate<T extends Fruit & ShowPrice & ShowCount> {
private T item;
public Plate(T item) {
this.item = item;
}
public void getName() {
item.getName();
}
public void showPrice() {
item.ShowPrice();
}
public void showCount() {
item.showCount();
}
public static void main(String[] args) {
Plate<Apple> applePlate = new Plate<>(new Apple());
applePlate.getName();
applePlate.showPrice();
applePlate.showCount();
}
}
此时,Plate 类只能接受实现了 ShowPrice 和 ShowCount 接口,并且必须为 Fruit 或 Fruit子类的参数。
此外,泛型参数的边界条件还可以通过继承来进行拓展。如下文所示,BigPlate 的泛型参数边界限制比 Plate 更加严格,必须额外实现一个 ShowSize 接口。
public interface ShowSize {
void showSize();
}
public class BigPlate<T extends Fruit & ShowPrice & ShowCount & ShowSize> extends Plate<T> {
public BigPlate(T item) {
super(item);
}
}
小结
1.泛型在未定义边界的情况下,默认被擦除为 Object ,无法调用泛型中的任何具体方法,定义边界后可突破此限制。
2.泛型的边界可定义多个限制条件,多个条件使用 & 进行连接。
3.泛型的边界可通过 extends 来继续向下拓展。
本次分享至此结束,希望本文对你有所帮助,若能点亮下方的点赞按钮,在下感激不尽,谢谢您的【精神支持】。
若有任何疑问,也欢迎与我交流,若存在不足之处,也欢迎各位指正!