下面是继承概念的测试程序。 如果我正在运行该程序,则输出为“Im A's method - 1”,如果我删除注释,则输出为“Im b's method - 2”。
class A {
public void test(int x){
System.out.println("Im A's method - 1");
}
public void test(Integer x){
System.out.println("Im A's method - 2");
}
}
class B extends A{
public void test(Integer x){
System.out.println("Im b's method - 1");
}
// public void test(int x){
// System.out.println("Im b's method - 2");
// }
//
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
A a=new B();
a.test(2);
}
}
<小时/>
问题:
据我所知,它不应该扩展到 A 类。请纠正我!!!
最佳答案
这是 Java 中动态绑定(bind)
的经典案例。因此,在阅读此评论后,您首先应该阅读一些有关 this 的内容。
第二个。它显示了我 A 的方法 - 1 因为看看你的 main
,你在说 A value = new B() code> 你说的是类似我有一辆汽车并且我希望它成为一辆汽车。
此外,您正在对 int
类型的值而不是 Integer
调用方法,因此它会调用 int
中需要 int
的方法code>B 的类。
因为您没有这样的方法,所以它会继续在父类(super class)中搜索它。
PS:如果您打算继续学习 Java 并在 Java 中工作,这是您在面试中会经常遇到的问题之一
关于java - 关于变量赋值和分配的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25480617/