public class Ex
{
public void eat(Animal animal){System.out.println("this is animal");}
public void eat(Dog dog){System.out.println("this is dog");}
public static void main(String[] args)
{
Ex ex=new Ex();
Animal animal=new Dog();
ex.eat(animal);
}
}
为什么这个程序给出输出:这是动物而不是这是狗,因为运行时实际实例是狗
最佳答案
因为它是在编译时决定调用哪个方法的。
一般来说,编译器无法决定变量的运行时类型(它是不可确定的),因此编译器会谨慎行事,并调用它确信会“工作”的方法。
标准的“解决方法”是使用 visitor pattern 。我在这里写了一个详细的例子:How to avoid large if-statements and instanceof
关于java - 为什么重载不支持多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4863451/