public class A {
public void method(Object val){
System.out.println("Class A's method method() called....");
}
}
public class B extends A {
public void method(String val){
System.out.println("Class B's method method() called....");
}
}
public class C extends B {
public void method(Integer val){
System.out.println("Class C's method method() called....");
}
public static void main(String[] args) {
A a = new C();
a.method(null);
}
}
为什么叫A的方法?想了解继承
最佳答案
这里没有歧义。
a
的编译时类型是类 A
。
类 A
只有一个名为 method
的方法 - public void method(Object val)
- 这是唯一可以使用的方法签名编译器在遇到 A
类型的变量时选择。
如果a
的编译时类型是C
,编译器会考虑所有三个method()
方法,这次它会提示歧义(因为它在 public void method(String val)
和 public void method(Integer val)
之间没有偏好)。
关于Java继承概念与不明确的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203183/