我正在查看我正在使用的一些代码,其中有一点特别让我印象深刻:
文件中有一个 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/