程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> JAVA構造時成員初始化的陷阱,java構造陷阱

JAVA構造時成員初始化的陷阱,java構造陷阱

編輯:JAVA綜合教程

JAVA構造時成員初始化的陷阱,java構造陷阱


讓我們先來看兩個類: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

原因分析:

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved