java多态参数适用于超类,但不适用于子类
我只是在学习多态性,所以请对我放松点(照本宣科)。我试图将一个类作为参数传递给一个方法。当我这样做时,我可以调用超类方法,但不能调用实际的子类。使用start()方法,我试图让狼嚎叫:
public class experiment {
public static void main(String[] args) {
PetOwner own = new PetOwner();
own.start();
}
}
//Trying polymorphic arguments
class Vet {
public void giveShot(Animal a) {
a.howl();
}
}
class PetOwner {
public void start() {
Vet v = new Vet();
Wolf w = new Wolf();
v.giveShot(w);
}
}
//Inheritance//
//Kingdom - Animal
class Animal {
public void move() {
System.out.println("*motions softly*");
}
}
//Family - canine
class Canine extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
//Species - wolf
class Wolf extends Canine {
public void howl() {
System.out.println("Howl! Howl!");
}
}
如果我将howl方法传递给超类(动物),它可以正常工作。如果我直接从Wolf类中调用它,它工作得很好。唯一一个不起作用的例子是,如果我试图将wolf类作为参数传递,并从那里调用它
以下是我这样尝试的原因,引自Head First Java第187页:
The Vet's giveShot() method can take any Animal you give it. As long as the object you in as the argument is a subclass of Animal, it will work
我收到一个“找不到符号:方法howl(),位置变量类型为animal”错误
共 (0) 个答案