如何从 Super::Super() 调用 Super::printThree?
在下面的示例中,我改为调用 Test::printThree。
class Super {
Super() {
printThree(); // I want Super::printThree here!
}
void printThree() { System.out.println("three"); }
}
class Test extends Super {
int three = 3
public static void main(String[] args) {
Test t = new Test();
t.printThree();
}
void printThree() { System.out.println(three); }
}
output:
0 //Test::printThree from Super::Super()
3 //Test::printThree from t.printThree()
你不能——它是一个在子类中被重写的方法;您不能强制调用非虚拟方法。如果要以非虚拟方式调用方法,请将该方法设为私有或最终。
一般来说,正是由于这个原因,在构造函数中调用非最终方法是一个坏主意 - 子类构造函数主体尚未执行,因此您实际上是在尚未完全执行的环境中调用方法已初始化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)