![](/img/trans.png)
[英]Can anyone explain to me the behavior of a nested for loop in Java in regards to memory?
[英]Java Puzzler - Can anyone explain this behavior?
abstract class AbstractBase {
abstract void print();
AbstractBase() {
// Note that this call will get mapped to the most derived class's method
print();
}
}
class DerivedClass extends AbstractBase {
int value = 1;
@Override
void print() {
System.out.println("Value in DerivedClass: " + value);
}
}
class Derived1 extends DerivedClass {
int value = 10;
@Override
void print() {
System.out.println("Value in Derived1: " + value);
}
}
public class ConstructorCallingAbstract {
public static void main(String[] args) {
Derived1 derived1 = new Derived1();
derived1.print();
}
}
上面的程序產生以下輸出:
Value in Derived1: 0
Value in Derived1: 10
我不明白為什么AbstractBase
構造函數中的print()
總是被映射到派生類最多的類(這里是Derived1
) print()
為什么不到DerivedClass
的print()
? 有人能幫助我理解這個嗎?
因為所有非顯式super
調用的Java方法調用都被調度到最派生類,即使在超類構造函數中也是如此。 這意味着超類可以獲得子類行為的好處,但這也意味着理論上可以在該類中的構造函數之前調用重寫方法。
超類構造函數中的虛擬化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.