2015-04-27 43 views
1

我有以下構件字段和構造一個類SomeClass甲包含相同類的另一個構造的構造/對象

private int someInt; 
private String someStr; 
private String strTwo; 

//the contructors 
public SomeClass() {} 

// second constructor 
public SomeClass(int someInt, String someStr) { 
    this.someInt = someInt; 
    this.someStr = someStr; 
} 

// my emphasis here 
public SomeClass(int someInt, String someStr, String strTwo) { 
    // can i do this 
    new SomeClass(someInt, someStr); // that is, calling the former constructor 
    this.strTwo = strTwo; 
} 

將在第三構造創建相同的對象爲:

public SomeClass(int someInt, String someStr, String strTwo) { 
    this.someInt = someInt; 
    this.someStr = someStr; 
    this.strTwo = strTwo; 
} 
+3

調用另一個構造函數完成這個(...)關鍵字 – nitegazer2003

+1

你是什麼意思'self.someInt'?它應該是'this.someInt'我想 –

回答

4

使用this關鍵字call a constructor from another constructor。如果你調用另一個構造函數,那麼它必須是構造函數體中的第一個語句。

public SomeClass(int someInt, String someStr, String strTwo) { 
    // Yes you can do this 
    this(someInt, someStr); // calling the former constructor 
    this.strTwo = strTwo; 
} 
2

不,至少不是你怎麼寫的。

您的第三個構造函數創建了new對象,然後將它的成員變量strTwo設置爲this對象。你基本上在這裏處理兩個單獨的對象。您在第三個構造函數中創建的對象將被垃圾回收,因爲在離開構造函數後沒有對其進行引用。

//This function is called when creating a new object with three params 
public SomeClass(int someInt, String someStr, String strTwo) { 
    new SomeClass(someInt, someStr); //Here you create a second new object 
    //Note that the second object is not set to a variable name, so it is 
    //immediately available for garbage collection 
    this.strTwo = strTwo; //sets strTwo on the first object 
} 

如果你的目標是創建一個對象,它是功能上與一個由兩個參數的構造函數創建的,你必須這樣做:

public SomeClass(int someInt, String someStr, String strTwo) { 
    this.SomeClass(someInt, someStr); 
    this.strTwo = strTwo; 
} 

這將是等效的代碼做所有成員字段集合在一個函數中,對象構造實際上如何到達最終產品只有很小的變化。與往常一樣,請注意,在這兩個函數之間創建的對象將相同,但不是「相同」對象:即它們將指向內存中保存相同值的不同位置。談論對象時,'相同'可能是一個棘手的詞。

2

您需要使用關鍵字「這」第三構造來代替:

public SomeClass(int someInt, String someStr, String strTwo) { 
// can i do this 
this(someInt, someStr); // that is, calling the former constructor 
this.strTwo = strTwo; 

}

那麼就應該有同樣的結果,是的。

相關問題