我想在同一個子類中調用父構造函數和另一個構造函數。這是否允許?另外,我知道this()
有一些限制(不得不先放置)super()
?我可以在同一個構造函數中調用兩者嗎?super()和this()是否出現在相同的構造函數中?
1
A
回答
3
在同一班,是的。
class Stuff extends Object
{
Stuff ()
{
super () ;
}
Stuff (int x)
{
this () ;
}
}
在相同的構造函數中,沒有。 super
或this
必須是構造函數中的第一件事。 如果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
只需撥打電話,以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;
}
}
相關問題
- 1. 爲什麼不能在構造函數中同時使用this()和super()?
- 2. 構造函數super()es6 angularjs
- 3. C#中的this()和base()構造函數
- 4. 根據參數在構造函數中調用不同的super()
- 5. Mockito.spy VerifyError:構造函數必須調用super()或this()
- 6. 在基類構造函數中使用`this`是否有效?
- 7. 您是否將super()調用作爲構造函數的開始?
- 8. `initialize`方法和構造函數是否相同?
- 9. 函數構造函數是否支持用`this`計算屬性?
- 10. 在Java中,有沒有什麼方法可以在同一個構造函數中調用this()和super()?
- 11. 調用base()和this()的構造函數
- 12. super()在構造函數中的含義是什麼?
- 13. jQuery在構造函數中打破「this」?
- 14. 在構造函數中使用'this'
- 15. 在構造函數中使用this()
- 16. PHP:在構造函數中使用$ this
- 17. this in javascript構造函數
- 18. java構造函數:this(。)
- 19. Java:抽象類構造函數和this()
- 20. 構造函數和關鍵字'this'
- 21. 瞭解構造函數和「this」
- 22. 用super構造函數初始化()
- 23. 在構造函數中拋出的異常:析構函數是否被調用?
- 24. 在構造函數中的「this」對象和CurrentThread之間
- 25. 在構造函數中調用不同類的構造函數?
- 26. super()在沒有繼承的類的構造函數中
- 27. 在Java類中具有super()和不具有super()函數調用的構造函數之間有什麼區別
- 28. 構造函數調用必須是super()中的構造函數中的第一條語句
- 29. 構造函數傳遞相同的int?
- 30. 在Java中,方法/構造函數聲明能否出現在另一個方法/構造函數聲明中?
你考慮嘗試嗎? – EJP 2012-03-12 01:12:49
我確實嘗試過,但我想了解它背後的規則。我想確保我不會對我嘗試過的東西感到幸運,而且類似的東西也會起作用。有時很難通過嘗試不同的組合來辨別整個圖像。我不是故意問一個壞問題。 – rubixibuc 2012-03-12 05:06:21