我想在同一个子类中调用父构造函数和另一个构造函数。这是否允许?另外,我知道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