java关于“的一些用法问题?”;?超级水果“;
我遇到了一个问题,例如: 水果类java关于“的一些用法问题?”;?超级水果“;,java,Java,我遇到了一个问题,例如: 水果类 public class Fruit extends Food { public static void main(String[] args) { Plate<? super Fruit> plate = new Plate<>(new Food()); plate.setItem(new Apple()); plate.setItem(new Food()); }
public class Fruit extends Food {
public static void main(String[] args) {
Plate<? super Fruit> plate = new Plate<>(new Food());
plate.setItem(new Apple());
plate.setItem(new Food());
}
static class Apple extends Fruit {
}
}
public class Food {
}
板材类'
public class Plate<T> {
private T item;
public Plate(T t) {
item = t;
}
public T getItem() {
return item;
}
public void setItem(T item) {
this.item = item;
}
}
是错误吗
这两种方法有什么区别
-就这些,谢谢 这条线上发生了两件事:
Plate<? super Fruit> plate = new Plate<>(new Food());
您正在设置一个盘子的项目。这个盘子
可以是任何东西的盘子,只要它是水果
或水果
的超类。这意味着传递食物
对象将不起作用。为什么?那么,如果plate
实际上是一个plate
?有可能,不是吗?编译器不知道
因此,您可以传递到plate.setItem
的唯一对象是水果
和水果
的子类,这是
在这里使用super
时,您创建了一些可以被消费但不能产生指定类型的东西。这正是你想要做的
为了简化一下,这里有一个示例,说明如何处理对象
Plate<? super Fruit> plate = new Plate<>(...);
Fruit fruit = plate.getItem(); // GOOD !
Food food = plate.getItem(); // GOOD ! Because even a Fruit can be assigned to a Food reference so it's OK !
Apple apple = plate.getItem(); // BAD ! No insurance it is an apple, we just know it is a Fruit
plate.setItem(new Fruit()); // GOOD !
plate.setItem(new Apple()); // GOOD ! Because we know it's always a Fruit, and Apple extends Fruit
plate.setItem(new Food()); // BAD ! No insurance we're not dealing with a Fruit, and a Food object can't be assigned to a Fruit reference (without casting)
PlatePlate
Plate<? super Fruit> plate = new Plate<>(new Food());
plate.setItem(new Food())
Plate<? super Fruit> plate = new Plate<>(...);
Fruit fruit = plate.getItem(); // GOOD !
Food food = plate.getItem(); // GOOD ! Because even a Fruit can be assigned to a Food reference so it's OK !
Apple apple = plate.getItem(); // BAD ! No insurance it is an apple, we just know it is a Fruit
plate.setItem(new Fruit()); // GOOD !
plate.setItem(new Apple()); // GOOD ! Because we know it's always a Fruit, and Apple extends Fruit
plate.setItem(new Food()); // BAD ! No insurance we're not dealing with a Fruit, and a Food object can't be assigned to a Fruit reference (without casting)