2012-03-12 44 views
1

我想在同一個子類中調用父構造函數和另一個構造函數。這是否允許?另外,我知道this()有一些限制(不得不先放置)super()?我可以在同一個構造函數中調用兩者嗎?super()和this()是否出現在相同的構造函數中?

+0

你考慮嘗試嗎? – EJP 2012-03-12 01:12:49

+0

我確實嘗試過,但我想了解它背後的規則。我想確保我不會對我嘗試過的東西感到幸運,而且類似的東西也會起作用。有時很難通過嘗試不同的組合來辨別整個圖像。我不是故意問一個壞問題。 – rubixibuc 2012-03-12 05:06:21

回答

3

在同一班,是的。

class Stuff extends Object 
{ 
     Stuff () 
     { 
      super () ; 
     } 

     Stuff (int x) 
     { 
      this () ; 
     } 
} 

在相同的構造函數中,沒有。 superthis必須是構造函數中的第一件事。 如果super是第一個,那麼this不能是第一個。 如果this是第一個,那麼super不能是第一個。 它們不能在相同的構造函數中共存。

1

您打電話給您的另一個構造函數this(),並在此構造函數中調用super()

0
// Call constructor overload in this class (below) 
public Foo(){ 
    this("Some stuff"); 
} 

// Call constructor overload in superclass. 
public Foo(String stuff){ 
    super(stuff) 
} 
+1

不接受問題。 – EJP 2012-03-12 01:14:21

+0

除外。示例代碼,顯示如何完成。 – 2012-03-12 01:31:28

+1

儘管解釋非常短暫。 [emory](http://stackoverflow.com/a/9660478/377270)和[hunter](http://stackoverflow.com/a/9660529/377270)都提供了有關如何撰寫出色答案的指導。 – sarnold 2012-03-12 01:46:07

1

只需撥打電話,以super()僅在構造函數中的一個:

public class Foo extends Bar 
{ 
    private int y; 

    public Foo(int x) 
    { 
     this(x, 0); 
    } 

    public Foo(int x, int y) 
    { 
     super(x); 
     this.y = y; 
    } 
} 

public class Bar 
{ 
    private int x; 

    public Bar(int x) 
    { 
     this.x = x; 
    } 
} 
相關問題