究竟什么是默认构造函数 - 你能告诉我以下哪一个是默认构造函数,以及它与其他构造函数的区别是什么?
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;
}
Run Code Online (Sandbox Code Playgroud) 对于重载的New或Factory样式方法,嵌套构造函数调用(从设计POV)是一个好主意吗?这主要适用于简单的构造函数,其中每个重载构建在前一个构建器上.
MyClass( arg1 ) {
_arg1 = arg1;
_otherField = true;
_color="Blue"
}
MyClass( arg1, arg2) : this(arg1) {
_arg2 = arg2
}
MyClass( arg1, arg2, arg3) : this(arg1, ar2) {
_arg3 = arg3;
}
Run Code Online (Sandbox Code Playgroud)
或者使用工厂方法:
static NewInstance(arg1 ) {
_arg1 = arg1;
}
static NewInstance(arg1, arg2) {
f = NewInstance(arg1);
f._arg2 = arg2;
}
//... and so on
Run Code Online (Sandbox Code Playgroud)
我可以看到双方都有一些弊端
所以,这样做是个好主意,还是让我为一些我没有看到的问题做好准备.出于某种原因,我感到不安,主要是因为它分担了初始化的责任.
编辑: @Jon Skeet:我现在明白为什么这太困扰我了.我倒退了!我写了整篇文章,甚至没有注意到,它只是闻到了.我所拥有的大多数其他情况(我写的),按你推荐的方式做,但这肯定不是我这样做的唯一一个.我注意到我做得比较复杂,但是我看起来很简单. 我喜欢微编辑.我也喜欢首字母缩略词!