为什么重载不支持多态

时间:2011-02-01 13:59:05

标签: java

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);
  }
}

为什么这个程序给出输出:这是动物而不是这是狗,因为实际的实例是Dog at runtime

2 个答案:

答案 0 :(得分:4)

因为在编译时决定要调用哪种方法。

一般情况下,编译器无法确定变量的运行时类型(它是不可判定的),因此编译器可以安全地播放它并调用它确定将“正常工作”的方法。

标准的“解决方法”是使用visitor pattern。我在这里写了一个详细的例子:How to avoid large if-statements and instanceof

答案 1 :(得分:0)

因为java不支持multiple dispatch ..但您可以通过Visitor pattern模拟双重调度行为。

相关问题