java - 代码调用 new GenericObject() 但 GenericObject.java 没有构造函数

标签 java compiler-construction constructor

我正在查看我正在使用的一些代码,其中有一点特别让我印象深刻:

文件中有一个 block :

public void prepare(){
    if (this.GenericObjectID != null) 
         doStuff();
    else{
         this.GenericObjet = new GenericObject();
    }

但是,当我查看 GenericObject.java 时,根本没有构造函数。代码运行了,但我没有写它,所以我不确定如何(还!)。所以我的问题是:这怎么可能?当 Java 编译器看到此调用但随后在描述该对象的文件中没有构造函数时,它在做什么?

最佳答案

如果没有显式构造函数,则编译器会创建一个隐式默认构造函数,不带任何参数,除了隐式调用父类(super class)构造函数之外什么都不做。

Section 8.8.9 of the JLS谈论默认构造函数:

If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

  • The default constructor has the same accessibility as the class (§6.6).

  • The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).

  • The default constructor has no throws clauses.

  • 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.

关于java - 代码调用 new GenericObject() 但 GenericObject.java 没有构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24895727/

相关文章:

macos - 在 Mac OS X 上捆绑私有(private) JRE

.net - 能否将 Phoenix 编译器用作更强大的 NGEN?

hibernate - 在构造函数中使用多对一集合的 SELECT NEW() - HQL

c++ - CRTP 基本构造函数崩溃,因为未构造子项

math - 数学指令如何在硬件上实现?

c++ - 不明白const对函数和类的使用

java - 重击 : jstat: command not found

java - 更改 Swing 的外观

java - 在此 Java Stream 用法中是否应该调用映射操作?

c++ - cppunit 中的 QTtestrunner 问题