java - 默认构造函数到底做了什么?

标签 java oop constructor

<分区>

关于默认构造函数在java中的真正作用,我有些不明白。在关于对象创建的官方教程中:

Creating Objects

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.

在有关默认构造函数的文档中 (§8.8.9)

8.8.9. Default Constructor

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

因此,即使是 Object 类的默认构造函数也有一个空主体。而且我知道默认构造函数NOT 将字段初始化为其默认值,因为它是编译器做的:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.

我不明白的是,如果我们不声明构造函数,默认构造函数到底做了什么?

最佳答案

what does the default constructor really do?

它调用super()。根据你所有的报价。并且什么都不做。 JLS #8.8.9 :

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

即它什么都不做。对于那些相信它会初始化实例变量的人,请参阅 JLS #12.5哪里有相反的断言。

关于java - 默认构造函数到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40524365/

相关文章:

android - 从类扩展 View 调用方法(使用构造函数)

java - 是否有一种标准方法可以将 Kotlin 序列转换为 java.util.Enumeration?

java - 如何初始化整个应用程序所需的对象?安卓

java - 不同 Java 类型之间的转换器

c# - 成员声明中 "new"的确切含义

php - 计算创建 PHP 类的次数

c++ - 如何在构造函数中使用 std::optional?

C++构造函数调用另一个构造函数

java - 如何在具有写权限的 Java 中获取原始磁盘访问权限 - Windows 7

java - 将点坐标转换为图像