Java 默认构造函数 [英] Java default constructor

查看:46
本文介绍了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.

除非您定义另一个构造函数,否则默认构造函数是自动生成的无参数构造函数.任何未初始化的字段都将设置为其默认值.对于您的示例,假设类型是 Stringintint,并且该类本身是公共的,它看起来像这样:

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 默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆