<分区>
我有下面的代码。看来我不能放类 Nonlife
的对象那是类的父类(super class) Vehicle
放入 Collection<? super Vehicle>
类型的容器中ALTHOUGH 通配符类型中有一个关键字“super”,并且只有 Vehicle
类的对象和 SUV
那是 Vehicle
类的子类是可行的。有人可以给我一些建议吗?
public class SUV extends Vehicle
public class Vehicle extends Nonlife implements Externalizable
public class Nonlife extends Thing
public class Thing implements Comparable<Thing>, Serializable
public class SupperWildcardTest20200830 {
public static void main(String[] args) {
Collection<Thing> coll = new ArrayList<>();
appendVehicle2Collection(coll);
appendSuv2Collection(coll);
for (Thing el: coll) {
System.out.println("" + el);
}
}
public static void appendVehicle2Collection(Collection<? super Vehicle> coll) {
coll.add(new Vehicle());
}
public static void appendSuv2Collection(Collection<? super Vehicle> coll) {
coll.add(new SUV());
}
public static void appendNolife2Collection(Collection<? super Vehicle> coll) {
/**
* incompatible types: Nonlife cannot be converted to CAP#1
* where CAP#1 is a fresh type-variable:
* CAP#1 extends Object super: Vehicle from capture of ? super Vehicle
*/
coll.add(new Nonlife());
}
}