Java 例項控制流


例項控制流是Java程式語言的一個基本概念,初學者和經驗豐富的程式設計師都必須瞭解。在Java中,例項控制流是類中成員執行的逐步過程。類中存在的成員包括例項變數、例項方法和例項塊。

每當我們執行Java程式時,JVM首先查詢main()方法,然後將類載入到記憶體中。接下來,類被初始化,並且如果存在靜態塊,則執行靜態塊。在執行靜態塊之後,例項控制流開始。在本文中,我們將解釋什麼是例項控制流。

Java 例項控制流

在上一節中,我們簡要介紹了例項控制流。在本節中,我們將透過示例程式詳細討論它。

例項控制流的過程涉及以下步驟:

  • 第一步是從上到下識別類的例項成員,例如例項變數、例項方法和例項塊。

  • 第二步是執行類的例項變數。例項變數宣告在類內但方法外。通常,要顯示它們的值,我們需要定義一個建構函式或方法。

  • 接下來,例項塊按其在類中出現的順序由JVM執行。這些塊是用於初始化例項變數的匿名塊。

  • 在第四步中,JVM呼叫類的建構函式來初始化物件。

  • 接下來,呼叫例項方法以執行其各自的操作。

  • 最後,呼叫垃圾收集器來釋放記憶體。

示例 1

以下示例演示了例項控制流的整個過程。

public class Example1 {
   int x = 10; // instance variable 
   // instance block
   {
      System.out.println("Inside an instance block"); 
   }
   // instance method
   void showVariable() {
      System.out.println("Value of x: " + x); 
   }
   // constructor
   Example1() {
      System.out.println("Inside the Constructor"); 
   }
   public static void main(String[] args) {
      System.out.println("Inside the Main method");
      Example1 exp = new Example1(); // creating object
      exp.showVariable(); // calling instance method
   }
}

輸出

Inside the Main method
Inside an instance block
Inside the Constructor
Value of x: 10

示例 2

以下示例說明了父子關係中的例項控制流。父類的例項成員在子類例項成員之前執行。

// creating a parent class
class ExmpClass1 {
   int x = 10; // instance variable of parent
   // first instance block
   {
      System.out.println("Inside parent first instance block"); 
   }
   // constructor of parent class
   ExmpClass1() {
      System.out.println("Inside parent constructor"); 
      System.out.println("Value of x: " + this.x);
   }
   // Second instance block
   {
      System.out.println("Inside parent second instance block"); 
   }
}
// creating a child class
class ExmpClass2 extends ExmpClass1 {
   int y = 20; // instance variable of child
   // instance block of child
   {
      System.out.println("Inside instance block of child"); 
   }
   // creating constructor of child class
   ExmpClass2() {
      System.out.println("Inside child constructor"); 
      System.out.println("Value of y: " + this.y);
   }
}
public class Example2 {
   public static void main(String[] args) {
      // creating object of child class
      ExmpClass2 cls = new ExmpClass2(); 
      System.out.println("Inside the Main method");
   }
}

輸出

Inside parent first instance block
Inside parent second instance block
Inside parent constructor
Value of x: 10
Inside instance block of child
Inside child constructor
Value of y: 20
Inside the Main method

結論

在本文中,我們瞭解了Java中例項控制流的整個過程。此過程中共有六個步驟。基本上,例項控制流告訴我們Java虛擬機器如何執行類的成員。

更新於:2023年7月20日

434 次檢視

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.