我试着去理解
为什么 this() 和 super() 不能一起使用?
我在这里阅读了很多关于 stackoverflow 的相关讨论,并且理解了很多东西。但我仍然有一个困惑。
calling this() inside a constructor implicitly calls super()
考虑这段代码..
class Top
{
int z;
Top()
{
System.out.println("Top default constructor");
}
}
class A extends Top
{
int x;
A(int num)
{
x=num;
System.out.println("A parameterized constructor");
}
A()
{
this(5);
System.out.println("A default constructor");
}
public static void main(String arg[])
{
new A();
}
}
输出是:
Top default constructor
A parametrized constructor
A default constructor
我没想到输出的第一行是“Top default constructor”,因为没有 super() 调用,无论是隐式的还是显式的。
所以我可能误解了一些东西。请解释。
最佳答案
Is it true that calling this() inside a constructor implicitly calls super()?
在构造函数中调用 this()
将调用该类的零参数构造函数。如果该类的零参数构造函数没有对 super(...)
的显式调用,那么是的,将会有一个对零参数的隐式调用-args super()
构造函数。如果您的类中的零参数构造函数显式调用了其他一些 super
签名,那么当然会这样做。
这对于一般的构造函数来说是正确的。在您的 A
类中,因为您的 A(int)
构造函数没有对 this()
或 super()
,隐式的 super()
完成了。
I was not expecting the first line in output "Top default constructor" as there is no
super()
call,implicit or explicit.
是的,有一个隐含的。 :-)
基本规则是:一些基类构造函数必须在派生类中的代码运行之前运行。这就是为什么调用 this(...)
或 super(...)
必须是构造函数中的第一个。如果构造函数没有对 super(...)
的显式调用,则总会有对 super()
的隐式调用(没有参数)。
关于java - 在构造函数中调用 this() 是否会隐式调用 super()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191532/