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>();
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下