【Java基礎】繼承中的代碼塊和構造方法的執行順序探索


本文講述有關一個類的靜態代碼塊,構造代碼塊,構造方法的執行流程問題。首先來看一個例子

/**
 * Created by lili on 15/10/19.
 */

class Person{
    static {
        System.out.println("執行Person靜態代碼塊");
    }

    {
        System.out.println("執行Person構造代碼塊");
    }
    public Person(){
        System.out.println("執行Person構造方法");
    }
}

class Student extends Person{
    static {
        System.out.println("執行Student靜態代碼塊");
    }

    {
        System.out.println("執行Student構造代碼塊");
    }
    public Student(){
        System.out.println("執行Student構造方法");
    }
}
public class ExtendsStaticConstruct {
    public static void main(String args[]){
        Student student = new Student();
    }

}

 

執行結果如下:

執行Person靜態代碼塊
執行Student靜態代碼塊
執行Person構造代碼塊
執行Person構造方法
執行Student構造代碼塊
執行Student構造方法

Process finished with exit code 0

 

 

說明程序的執行順序是:

  靜態代碼塊 ---》    構造代碼塊 ----》  構造方法

執行流程解釋:
  new的是Student類,但是Student是繼承子Person類,所以在加載Student類時先要加載Person類,而靜態的內容是隨着類的加載而加載的,所以先打印“執行Person靜態代碼塊”,后執行Student的靜態代碼塊。

  加載完類后,開始走main方法,執行Student構造方法上,即初始化Student,但是Student是繼承自Person,必須先初始化Person,所以先調用Person類的空參構造方法進行初始化,但是Person類的構造代碼塊優先於構造方法執行,所以Person類的構造代碼塊先執行,構造方法后執行。然后再執行Student類的構造代碼塊和構造方法。

  這里的執行順序同子類構造中有一個默認的父類構造super()無關,不是執行到隱藏的super()才開始初始化父類的,類的初始化是分層初始化,即先初始化父類,再初始化子類,初始化每個類的過程中,進行類的初始化工作,先進性成員變量的初始化,成員變量的初始化順序是:默認初始化,即int為0這種--》顯示初始化,例如給int型顯示初始化了值--》構造方法初始化,所以是這里執行到了構造方法。

      但是一定要注意,父類初始化選擇的構造方法卻和子類中super 選擇的構造相關,下面代碼很好的解釋了這點。

 

/**
 * Created by lili on 15/10/19.
 */

class Person{
    static {
        System.out.println("執行Person靜態代碼塊");
    }

    {
        System.out.println("執行Person構造代碼塊");
    }

    public Person(){
        System.out.println("執行Person無參構造方法");
    }

    public Person(String name){
        System.out.println("執行Person構造方法"+ name);
    }
}

class Student extends Person{

    static {
        System.out.println("執行Student靜態代碼塊");
    }
    {
        System.out.println("執行Student構造代碼塊");
    }
    public Student(String name){
        super(name);
        System.out.println("執行Student構造方法" + name);
    }
    public Student(){
        super();
        System.out.println("執行Student無參構造方法");
    }




}
public class ExtendsStaticConstruct {
    public static void main(String args[]){
        Student student1 = new Student("lili");

        System.out.println("--------------------");
        Student student2 = new Student();

    }

}

 

結果:

執行Person靜態代碼塊
執行Student靜態代碼塊
執行Person構造代碼塊
執行Person構造方法lili
執行Student構造代碼塊
執行Student構造方法lili
--------------------
執行Person構造代碼塊
執行Person無參構造方法
執行Student構造代碼塊
執行Student無參構造方法

Process finished with exit code 0

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM