【发布时间】:2016-06-12 18:47:36
【问题描述】:
据我了解,Java 中的所有函数调用都是虚拟的,而数字文字的类型为 int。但是为什么下例中的输出不同呢?
public class A {
public int f(long d) {
return 2;
}
}
public class B extends A {
public int f(int d) {
return 1;
}
}
public class M {
public static void main(String[] args) {
B b = new B();
A ab = b;
System.out.println(b.f(1));
System.out.println(ab.f(1));
}
}
【问题讨论】:
-
A没有定义任何f(int)方法,所以很明显,f(long)在第二种情况下被调用。您的代码中没有方法覆盖。