讓我們先來看兩個類:Base和Derived類。註意其中的whenAmISet成員變數,和方法preProcess()。 情景1:(子類無構造方法) 當.java源代碼轉換成一個.class文件後,其轉換成類似下麵的等價代碼: 輸出結果是: set when declared 情景2:(子類添加了構 ...
讓我們先來看兩個類:Base和Derived類。註意其中的whenAmISet成員變數,和方法preProcess()。
情景1:(子類無構造方法)
class Base { Base() { preProcess(); } void preProcess() { } } class Derived extends Base { public String whenAmISet = "set when declared"; void preProcess() { whenAmISet = "set in preProcess()"; } } public class StaticTest { public static void main(String[] args) { Derived d = new Derived(); System.out.println(d.whenAmISet); } }
當.java源代碼轉換成一個.class文件後,其轉換成類似下麵的等價代碼:
class Base { Base() { preProcess(); } void preProcess() { } } class Derived extends Base { public String whenAmISet; {whenAmISet = "set when declared";} void preProcess() { whenAmISet = "set in preProcess()"; } } public class StaticTest { public static void main(String[] args) { Derived d = new Derived(); System.out.println(d.whenAmISet); } }
輸出結果是: set when declared
情景2:(子類添加了構造方法)
class Base { Base() { preProcess(); } void preProcess() { } } class Derived extends Base { public String whenAmISet = "set when declared"; public Derived() { whenAmISet = "set in constructor"; } void preProcess() { whenAmISet = "set in preProcess()"; } } public class StaticTest { public static void main(String[] args) { Derived d = new Derived(); System.out.println(d.whenAmISet); } }
當.java源代碼轉換成一個.class文件後,其轉換成類似下麵的等價代碼:
class Base { Base() { preProcess(); } void preProcess() { } } class Derived extends Base { public String whenAmISet; public Derived() { whenAmISet = "set when declared"; whenAmISet = "set in constructor"; } void preProcess() { whenAmISet = "set in preProcess()"; } } public class StaticTest { public static void main(String[] args) { Derived d = new Derived(); System.out.println(d.whenAmISet); } }
輸出結果為:set in constructor
原因分析:
- 陳皓博客
- Java Tutor - Visualize Java code execution to learn Java online (also visualize Python, Java, JavaScript, TypeScript, Ruby, C, and C++ code)