鉴于以下代码块,我想了解为什么以及如何,强调如何,子类中的打印方法被调用:
class Super {
Super() {
// what happens so that Sub's method print() is invoked
print();
}
public void print() {
System.out.println("in super");
}
}
class Sub extends Super {
Sub() {
super();
}
public void print() {
System.out.println("in sub");
}
}
public class TestClass {
public static void main(String[] args) {
Super s = new Sub(); // "in sub".. not so much expected
s.print(); // "in sub".. as expected
}
}
我的理解是,在编译期间,类将获得与“属于”类的方法关联的 V 表指针vtblPtr
。
因此,Super
类应该引用它自己的方法 print()
实现。
Super
的构造函数中如何调用Sub
中的print()
方法?这里到底发生了什么?
最佳答案
这是 JVM 的 Super
类(实际上,这是通过 javap -c Super
获得的人类可读版本)
class Super {
Super();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: invokevirtual #2 // Method print:()V
8: return
public void print();
Code:
0: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #4 // String in super
5: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}
如您所见,Super
构造函数中的 print
在编译时未解析为 Super::print
。虚拟调用意味着它在运行时根据 this
的类进行解析。
关于java - 从父类(super class)构造函数调用基类覆盖的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33215452/