Java默认构造函数 [英] Java default constructor
问题描述
默认构造函数究竟是什么? - 你能告诉我下面哪一个是默认构造函数,以及它与其他构造函数的区别吗?
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. It initialises any uninitialised fields to their default values. For your example, it would look like this assuming that the types are String
, int
and int
:
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语言规范
在技术上,它不是默认初始化字段的构造函数(默认或其他)。但是,我把这个留在答案
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving this in the answer as
- 问题得到了默认值错误和
- 包括它们与否,构造函数具有完全相同的效果。
这篇关于Java默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!