簡體   English   中英

無法理解程序工作流程

[英]Unable to understand program work flow

// filename: Test2.java
class Test1 {   
    Test1(int x) {
        System.out.println("Constructor called " + x);
    }
}

// This class contains an instance of Test1 
class Test2 {    
    Test1 t1 = new Test1(10);   

    Test2(int i) { t1 = new Test1(i); } 

    public static void main(String[] args) {    
         Test2 t2 = new Test2(5);
    }
}

Output:
Constructor called 10
Constructor called 5

誰能解釋這個程序的輸出? 我不知道如何打印“ 構造函數稱為10 ”。 提前致謝。

  • 您的main調用Test2的構造函數。
  • 在執行該構造函數的主體之前,將初始化該類的所有實例變量。
  • 這包括Test1 t1 = new Test1(10); 它使用參數10執行Test1的構造函數,並顯示“被稱為10的構造函數”。
  • 然后,才執行Test2構造函數的主體,其中包括t1 = new Test1(i); ,它使用參數i (其值為5)執行Test1的構造函數,並顯示“被稱為5的構造函數”。

在您的Test2類中,您通過調用Test1的構造函數並傳入值10創建了Test1的實例。

Test1 t1 = new Test1(10);

在構造函數內部是一個print語句,該語句打印傳遞給構造函數的值。

Test1(int x) {
    System.out.println("Constructor called " + x);
}

這是您的輸出來源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM