Java default constructor(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
- 问题的默认设置错误,并且
- 无论是否包含构造函数,其效果完全相同.
这篇关于Java 默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 默认构造函数


基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01