java靜態代碼塊、非靜態代碼塊、構造方法和靜態方法的執行順序

1 靜態代碼塊:有些代碼必須在項目啓動的時候就執行,這種代碼是主動執行的(當類被載入時,靜態代碼塊被執行,且只被執行一次,靜態塊經常使用來執行類屬性的初始化)spa

2 靜態方法:須要在項目啓動的時候就初始化,在不建立對象的狀況下,這種代碼是被動執行的(靜態方法在類加載的時候就已經加載 能夠用類名直接調用)。code

二者的區別是:靜態代碼塊是自動執行的,對象

靜態方法是被調用的時候才執行的.blog

靜態代碼塊,在虛擬機加載類的時候就會加載執行,並且只執行一次;虛擬機

非靜態代碼塊,在建立對象的時候(即new一個對象的時候)執行,每次建立對象都會執行一次class

不建立類執行靜態方法並不會致使靜態代碼塊或非靜態代碼塊的執行。test

 

不建立類執行靜態方法並不會致使靜態代碼塊或非靜態代碼塊的執行,示例以下:方法

package com.practice.dynamicproxy;

class Parent {
    static String name = "hello";
    {
        System.out.println("parent block");
    }
    static {
        System.out.println("parent static block");
    }

    public Parent() {
        System.out.println("parent constructor");
    }
    
}

class Child extends Parent {
    static String childName = "hello";
    {
        System.out.println("child block");
    }
    static {
        System.out.println("child static block");
    }

    public Child() {
        System.out.println("child constructor");
    }
}

public class StaticIniBlockOrderTest {
    public static void test1() {
        System.out.println("static method");
    }
    public static void main(String[] args) {
//        new Child();// 語句(*)
//        new Child();
        StaticIniBlockOrderTest.test1();
    }
}

執行的結果以下:項目

static methodstatic

 

其他的示例代碼以下:

package com.practice.dynamicproxy;

class Parent {
    static String name = "hello";
    {
        System.out.println("parent block");
    }
    static {
        System.out.println("parent static block");
    }

    public Parent() {
        System.out.println("parent constructor");
    }
    
}

class Child extends Parent {
    static String childName = "hello";
    {
        System.out.println("child block");
    }
    static {
        System.out.println("child static block");
    }

    public Child() {
        System.out.println("child constructor");
    }
}

public class StaticIniBlockOrderTest {
    public static void test1() {
        System.out.println("static method");
    }
    public static void main(String[] args) {
        new Child();// 語句(*)
        new Child();
//        StaticIniBlockOrderTest.test1();
    }
}

執行的結果以下:

parent static block
child static block
parent block
parent constructor
child block
child constructor
parent block
parent constructor
child block
child constructor

說明:靜態代碼塊的只會執行一次,非靜態代碼塊執行兩次,先執行父類的非靜態代碼塊和構造器,再執行本類的非靜態代碼塊和構造器

相關文章
相關標籤/搜索