java - 在构造函数中调用 this() 是否会隐式调用 super()?

标签 java class constructor

我试着去理解

为什么 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/

相关文章:

java - 在 mysql 中的 INSERT-WHERE 查询中嵌套 SELECT-WHERE 查询

java - 如何浏览h2数据库

C++矩阵类: overloading assignment operator

c++ - 可以安全地使用复制/移动构造函数来实现复制/移动赋值运算符吗?

c++ - 构造后调用 delete 抛出异常

java - 为什么我找不到 ProgressiveMediaSource?

java - 将 int char 转换为 int 而不改变 java 中的值

c# - 可变 watch 突然停止工作(VS)

java - 从匿名类中检索数据

c++ - 主要 C++ 的类问题