这是代码:
class Override {
public static void main(String[] args) {
A a = new A(1, 2);
A a1 = new B(1, 2, 3);
B b = new B(4, 5, 6);
a.show();
a1.show();
b.show();
}
}
class A {
int a;
int b;
A(int a, int b) {
this.a = a;
this.b = b;
}
void show() {
System.out.println(a + " " + b);
}
}
class B extends A {
int c;
B(int a, int b, int c) {
super(a, b);
this.c = c;
}
void show() {
System.out.println(c);
}
}
结果:
1 2
3
6
父类(super class)的引用变量可以分配给从该父类(super class)派生的任何子类的对象。 引用变量的类型决定了可以访问哪些成员。
基于上述事实,a1无法访问c(B的成员),因为a1不知道B中任何成员的存在。我的问题是当a1调用show()时,为什么show( )在 B 中被调用而不是 A 中?
感谢大家的回答。
这是我认为非常有趣的事情:
动态方法分派(dispatch)是一种在运行时解析对重写方法的调用的机制。 当通过父类(super class)引用调用重写的方法时,java 根据调用发生时所引用的对象的类型确定要执行该方法的哪个版本。
最佳答案
因为 B
重写了 show()
方法,所以 B
中的 show()
被调用。考虑一个 abstract
方法,如果 B
无法替换抽象方法,则它永远无法实现(与接口(interface)一样)。
abstract void show();
最后,如果该方法不应被重写,请将其设为私有(private)
。默认的访问级别是继承的。
关于java - 当分配给子类对象的父类(super class)引用调用重写方法时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116266/