2025-02-10

本文講解Java中類的執行順序
順序應該是這樣的:父類Static->子類static->父類缺省{}->父類構造函數->子類缺省{}->子類構造函數
所以上面的例子打印順序應該是這樣的:
parent static block 父類Static
child static block 子類static
parent  block 父類缺省{}
parent constructor 父類構造函數
child  block子類缺省{}
child constructor子類構造函數
class Parent{
     static String name = “hello”;
     static {
         System.out.println(“parent static block”);
     }
     {
         System.out.println(“parent block”);
     }
     public Parent(){
         System.out.println(“parent constructor”);
     }
 }
   
 class Child extends Parent{
     static String childName = “hello”;
     static {
         System.out.println(“child static block”);
     }
     {
         System.out.println(“child block”);
     }
     public Child(){
         System.out.println(“child constructor”);
     }
 }
   
 public class StaticIniBlockOrderTest {
   
     public static void main(String[] args) {
         new Child();//語句(*)

     }
 }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *