1 靜態代碼塊:有些代碼必須在項目啟動的時候就執行,這種代碼是主動執行的(當類被載入時,靜態代碼塊被執行,且只被執行一次,靜態塊常用來執行類屬性的初始化)
2 靜態方法:需要在項目啟動的時候就初始化,在不創建對象的情況下,這種代碼是被動執行的(靜態方法在類加載的時候就已經加載 可以用類名直接調用)。
兩者的區別是:靜態代碼塊是自動執行的,
靜態方法是被調用的時候才執行的.
靜態代碼塊,在虛擬機加載類的時候就會加載執行,而且只執行一次;
非靜態代碼塊,在創建對象的時候(即new一個對象的時候)執行,每次創建對象都會執行一次
不創建類執行靜態方法並不會導致靜態代碼塊或非靜態代碼塊的執行。
不創建類執行靜態方法並不會導致靜態代碼塊或非靜態代碼塊的執行,示例如下:
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 method
其余的示例代碼如下:
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
說明:靜態代碼塊的只會執行一次,非靜態代碼塊執行兩次,先執行父類的非靜態代碼塊和構造器,再執行本類的非靜態代碼塊和構造器