2010-11-11 58 views
9

this()在Java中的含義是什麼?Java中this()的含義是什麼

它看起來在類變量區把

this(); 

當它是唯一有效的。

任何人都有這個想法?

謝謝。

+0

我在其他帖子上回答了類似的問題。可能會有所幫助http://stackoverflow.com/questions/15867722/java-this-method-confusion – Avi 2013-04-09 23:13:14

回答

7

這意味着你正在調用另一個構造函數的默認構造函數。它必須是第一條語句,如果有,就不能使用super()。使用它是相當罕見的。

+0

@Byron,歡呼聲。 – 2010-11-11 18:58:06

1

調用this() wil調用沒有參數的類的構造函數。

你會使用這樣的:

public MyObj() { this.name = "Me!"; } 
public MyObj(int age) { this(); this.age = age; } 
+1

哦,上帝......不要那樣做! public MyObj(){this(「Me!」);} public MyObj(String nm){this(name,0);} MyObj(String nm,int a){name = nm;年齡= a; } – TofuBeer 2010-11-11 19:07:22

+0

'function'不是Java關鍵字 – barrowc 2010-11-12 03:22:36

+0

@barrow:再次混合我的語言,謝謝。 – 2010-11-12 13:51:57

3

它表示「無參數的調用構造函數」。例如:

public class X { 
    public X() { 
     // Something. 
    } 
    public X(int a) { 
     this(); // X() will be called. 
     // Something other. 
    } 
} 
+0

很好解釋。謝謝 – Jay 2010-11-11 18:53:54

0

類調​​用自身的默認構造函數顯式調用構造函數。用論據來看它更常見。

6

這是對無參構造函數的調用,您可以調用它作爲另一個構造函數中的第一條語句以避免重複代碼。

public class Test { 

     public Test() { 
     } 

     public Test(int i) { 
      this(); 
      // Do something with i 
     } 

}