2015-11-03 209 views
-3

我正在討論在下面的示例中創建了多少個對象。我相信應該有5個,但我不太確定。創建了多少個對象 - Java

class Test { 
    int a; int b; 
    Test(){ 
    } 
    Test(int a_, int b_){ 
     a=a_; b=b_; 
    } 
    Test(Test r){ 
     a=r.a; b=r.b; 
    } 
    void povecaj() { 
     a++; b++; 
    } 
    Test dodaj(Test r) 
     Test t = new Test(a+r.a, b+r.b); 
     return t; 
    } 
} 

// ... 
Test t1 = new Test(); 
Test t2 = new Test(1, 2); 
t1.povecaj(); 
Test t3 = new Test(t2); 
t1 = t1.dodaj(t3); 
t2 = t3; 
+0

使用調試器。 ... – redFIVE

+0

4. 13個字符去。 –

+0

@MarkSeygan 4個對象? – user3047285

回答

1

可以創建新對象explicitly or implicitly

隱式創建可以發生在字符串文字,字符串連接,自動裝箱。在Java 8中,它也可以在方法引用表達式和lambda表達式中出現。

您顯示的代碼不包含任何隱式對象創建。它也沒有調用任何可能會創建對象的外部代碼。

因此,通過調用new明確創建由此代碼創建的所有對象。 此代碼調用new四次,因此創建了四個對象。

Test t1 = new Test();  // One 
Test t2 = new Test(1, 2); // Two 
t1.povecaj(); 
Test t3 = new Test(t2); // Three 
t1 = t1.dodaj(t3);   // Four, in the method implementation 
3

其實,你創建Test型的4個對象與你的小程序。在這個簡單的程序中,您可以輕鬆地統計new關鍵字的出現次數。

您可以通過代碼或者調試......或者保持靜態計數變量檢查:

class Test { 
    static int count; // used for counting instance creations 

    int a; 
    int b; 

    Test() { 
     count += 1; // new instance created => increment count 
    } 

    Test(int a_, int b_) { 
     this(); // Absolutely needed to have the counter incremented! 
     a = a_; 
     b = b_; 
    } 

    Test(Test r) { 
     this(); // Absolutely needed to have the counter incremented! 
     a = r.a; 
     b = r.b; 
    } 

    void povecaj() { 
     a++; 
     b++; 
    } 

    Test dodaj(Test r) { 
     Test t = new Test(a + r.a, b + r.b); 
     return t; 
    } 

    public static void main(String[] args) { 
     Test t1 = new Test(); 
     Test t2 = new Test(1, 2); 
     t1.povecaj(); 
     Test t3 = new Test(t2); 
     t1 = t1.dodaj(t3); 
     t2 = t3; 
     System.out.println(count); 
    } 
} 

這將打印