小编典典

Java默认构造函数

java

默认构造函数到底是什么?你能告诉我以下哪个是默认构造函数,它与其他构造函数有何不同?

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;
}

阅读 594

收藏
2020-02-26

共1个答案

小编典典

他们都不是。如果定义,则不是默认值。

除非你定义另一个构造函数,否则默认构造函数是自动生成的无参数构造函数。任何未初始化的字段都将设置为其默认值。对于你的榜样,它看起来像这样假设的类型String,int以及int,那类本身是公共的:

public Module()
{
  super();
  this.name = null;
  this.credits = 0;
  this.hours = 0;
}

这与

public Module()
{}

完全没有构造函数。但是,如果定义至少一个构造函数,则不会生成默认构造函数。

2020-02-26