java - 默认构造函数链接

标签 java constructor default-constructor

(true 或 false)如果您编写的构造函数的第一个语句不是对另一个构造函数的调用,则插入默认构造函数调用。

这个问题的答案是正确的。 然后我尝试创建了一些链式构造函数。

public class Temp {
     // default constructor 1
    Temp()
    {
        System.out.println("default");
    }

    // parameterized constructor 2
    Temp(int x)
    {
        System.out.println(x);
    }

    public static void main(String args[])
    {

        new Temp(8);
    }
}

输出:

8

未打印“默认”。所以我认为默认构造函数没有被调用。答案应该是假的。有人能解释一下为什么吗?

最佳答案

来自Java SE 8 Specification :

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

所以a default constructor call in inserted. ,但它是您的父类(super class)的默认构造函数(在本例中: Object )而不是您声明的类。

关于java - 默认构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412715/

相关文章:

java - react 堆: function creating Monos to Flux

c++ - 优化构造函数调用次数

c++ - 使用构造函数参数实例化类对象和不带参数 C++ 的 * 运算符之间的区别

java - 将 Arraylist 从 fragment 传递到其自己的 Activity

java - 运行 gradle clean build 时遇到问题

java - 在 Java Swing 中渲染高清视频?太慢了?

c++ - "Ambiguous resolution"选择性构造函数继承错误

c++ - ctor init 不调用库中的全局 ctor 实例

c# - 在 C# 中构建结构时出错

使用从抽象类继承的 C++ 默认构造函数