讓我們先來看兩個類:Base和Derived類。注意其中的whenAmISet成員變量,和方法preProcess()。
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
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