为什么Java不允许我执行这种类型的多态/继承?

Luc*_*lio 2 java polymorphism inheritance

我正在重构一个巨大的if语句.我发现改进它的方法之一是使用多态和继承.以非常简单的方式,这是我在我的代码中所拥有的:

public abstract class Animal {  
    public abstract void doAction();  
}

public class Dog extends Animal {  
    public void doAction() {System.out.println("run");} 
}

public class Cat extends Animal {  
    public void doAction() {System.out.println("sleep");}
}

public class RunActions {  
    public void runAction(Dog d) {
        d.doAction();
    }

    public void runAction(Cat c) {
        c.doAction();
    }
}

public class Start {
    public static void main(String args[]) {
        Animal animal = new Dog();
        new RunActions().runAction(animal); // Problem!
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我知道.我可以调用animal.doAction();. 或者在RunActions中添加一个接收Animal作为参数的方法.

但为什么编译器不允许我调用最后一个"runAction(animal)"行?JVM不应该弄清楚动物是运行时Dog的一个实例吗?

是否有特定原因导致我不允许这样做?

编辑:忘了让狗和猫延伸动物.固定.

jlo*_*rdo 5

编译器无法保证在运行时存在适当的方法.

你有一个方法,需要一个Cat,你有一个方法,需要一个Dog.您正在尝试传递Animal引用a 的变量Dog.怎么会引用Elephant?然后在运行时没有合适的方法.这就是为什么它不会让你编译.

Animal animal = new Elephant();
new RunActions().runAction(animal); // real problem now!
Run Code Online (Sandbox Code Playgroud)