Java创建有界的泛型类
示例
您可以通过限制类定义中的类型来限制通用类中使用的有效类型。给定以下简单的类型层次结构:
public abstract class Animal {
public abstract String getSound();
}
public class Cat extends Animal {
public String getSound() {
return "Meow";
}
}
public class Dog extends Animal {
public String getSound() {
return "Woof";
}
}如果没有有界的泛型,我们就不能创建既是泛型又知道每个元素都是动物的容器类:
public class AnimalContainer<T> {
private Collection<T> col;
public AnimalContainer() {
col = new ArrayList<T>();
}
public void add(T t) {
col.add(t);
}
public void printAllSounds() {
for (T t : col) {
//非法,类型T没有makeSound()
//它在这里用作java.lang.Object
System.out.println(t.makeSound());
}
}
}通过类定义中的泛型绑定,现在可以做到这一点。
public class BoundedAnimalContainer<T extends Animal> { //请注意此处。
private Collection<T> col;
public BoundedAnimalContainer() {
col = new ArrayList<T>();
}
public void add(T t) {
col.add(t);
}
public void printAllSounds() {
for (T t : col) {
//现在有效,因为T正在扩展Animal
System.out.println(t.makeSound());
}
}
}这也限制了泛型类型的有效实例化:
//法律 AnimalContainer<Cat> a = new AnimalContainer<Cat>(); //法律 AnimalContainer<String> a = new AnimalContainer<String>();
//法律 because Cat extends Animal BoundedAnimalContainer<Cat> b = new BoundedAnimalContainer<Cat>(); //非法,因为String不能扩展Animal BoundedAnimalContainer<String> b = new BoundedAnimalContainer<String>();
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志