Java 默认构造函数
究竟什么是默认构造函数——你能告诉我以下哪一个是默认构造函数以及它与任何其他构造函数的区别吗?
What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
推荐答案
两者都不是.如果你定义它,它就不是默认的.
Neither of them. If you define it, it's not the default.
除非您定义另一个构造函数,否则默认构造函数是自动生成的无参数构造函数.任何未初始化的字段都将设置为其默认值.对于您的示例,假设类型是 String
、int
和 int
,并且该类本身是公共的,它看起来像这样:
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String
, int
and int
, and that the class itself is public:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
这完全一样
public Module()
{}
和完全没有构造函数完全一样.但是,如果您定义了至少一个构造函数,则不会生成默认构造函数.
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
参考:Java 语言规格
如果一个类不包含构造函数声明,则隐式声明一个没有形式参数且没有 throws 子句的默认构造函数.
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
澄清
从技术上讲,默认初始化字段的不是构造函数(默认或其他).但是,我将其保留为答案,因为
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
- 问题的默认设置错误,并且
- 无论是否包含构造函数,其效果完全相同.
相关文章