超级绑定示例
引入的
transferTo()方法接受
Cage<? super T>-持有的超类的Cage
T。因为T是一个instanceof它的超类,它的确定,把
T在
Cage<? super T>。
public static class Cage<T extends Animal> { private Set<T> pen = new HashSet<T>(); public void add(T animal) { pen.add(animal); } public void transferTo(Cage<? super T> cage) { cage.pen.addAll(this.pen); } public void showAnimals() { System.out.println(pen); }}现在让我们看一下
<? super T>实际操作:
public static class Animal { public String toString() { return getClass().getSimpleName(); }}public static class Rat extends Animal {}public static class Lion extends Animal {}public static class Cage<T extends Animal> { }public static void main(String[] args) { Cage<Animal> animals = new Cage<Animal>(); Cage<Lion> lions = new Cage<Lion>(); animals.add(new Rat()); // OK to put a Rat into a Cage<Animal> lions.add(new Lion()); lions.transferTo(animals); // invoke the super generic method animals.showAnimals();}输出:
[Rat, Lion]
另一个重要的概念是:
Lion instanceof Animal // true
这 不是 真的
Cage<Lion> instanceof Cage<Animal> // false
如果不是这种情况,则此代码将编译:
Cage<Animal> animals;Cage<Lion> lions;animals = lions; // This assignment is not allowedanimals.add(rat); // If this executed, we'd have a Rat in a Cage<Lion>



