Java 中的非靜態塊。


靜態塊是帶靜態關鍵字的程式碼塊。通常,這些靜態塊用於初始化靜態成員。在類載入時,JVM 在主方法之前執行靜態塊。

示例

 即時演示

public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

輸出

Hello this is a static block
This is main method

例項初始化塊

與靜態塊類似,Java 也提供例項初始化塊,該塊用於初始化例項變數,以替代建構函式。

每當你定義一個初始化塊時,Java 會將其程式碼複製到建構函式中。因此,你還可以使用它們在類的建構函式之間共享程式碼。

示例

 即時演示

public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

輸出

25
Krishna

在一個類中,你還可以有多個初始化塊。

示例

 即時演示

public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   {
      System.out.println("Initialization block");
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

輸出

Initialization block
25
Krishna

你還可以定義父類中的例項初始化塊。

示例

public class Student extends Demo {
   String name;
   int age;
   {
      System.out.println("Initialization block of the sub class");
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

輸出

Initialization block of the super class
Initialization block of the sub class
25
Krishna

更新於: 2019 年 9 月 6 日

3K+ 檢視次數

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告