class Aquatic extends Animal {
boolean scale;
Aquatic(long years,float kg, boolean skin){
super(years,kg);
scale=skin;
}
public void print() {
super.print();
System.out.println(scale);
}
}
public class Animal {
long lifespan;
float weigh;
Animal(long years,float kg){
lifespan=years;
weigh=kg;
}
public void print() {
System.out.println(lifespan);
System.out.println(weigh);
}
}
public class AnimalWorld <T extends Animal>{ //scope of Animal and its sub classes
T[] ListOfAnimals;
AnimalWorld(T[] list){
ListOfAnimals=list;
}
}
public class BoundedWildcardArgumentsDemo {
static void vitality(AnimalWorld<?> animal) {
for(Animal a: animal.ListOfAnimals)
a.print();
System.out.println();
}
static void showSea(AnimalWorld<? super Aquatic> animals) {
for(Object obj: animals.ListOfAnimals) {
obj.print(); // This gives error that "method print is undefined for type object
}
}
public static void main(String args[]) {
Animal unknown=new Animal(40,720);
Animal u[]= {unknown};
AnimalWorld<Animal> uList=new AnimalWorld<>(u);
vitality(uList);
}
}
我的Animal类自然应该继承Object类,因此print()应该为obj定义。甚至当我添加Animal extends Object时,我又得到了同样的错误。根据我对继承的理解,obj应该能够访问print()方法。我错过什么了吗?
您只需在boundedwildcardarumentsdemo类的showSea()方法中更改对象的类型。您必须更改"对象"。到"动物物件">
:
static void showSea(AnimalWorld<? super Aquatic> animals) {
for(Object obj: animals.ListOfAnimals) {
obj.print(); // This gives error that "method print is undefined for type object
}
}
:后
static void showSea(AnimalWorld<? super Aquatic> animals) {
for(Animal obj: animals.ListOfAnimals) {
obj.print(); // This gives error that "method print is undefined for type object
}
}
对象obj"没有"打印"方法,因此您应该将其设置为抽象父类的类型,为"animal"。