Jea*_*ett 10 java oop constructor
我的BigBlock类需要一些重载的构造函数.所有这些都需要以相同的方式初始化相同的几个字段.
这样做的正确方法是什么?是否要创建一个函数,例如Initialize在下面的示例中,执行这些操作,并让所有构造函数调用该函数?
public class BigBlock {
private Thing parentThing;
Units lengthUnit;
LabCoordinateSystem labCoordinateSystem;
private void Initialize(){
lengthUnit = parentThing.getPreferredUnits(0);
labCoordinateSystem = parentThing.getCoordinateSystem();
}
BigBlock(Thing myThing){
parentThing= myThing;
Initialize();
}
BigBlock(Thing myThing, double x, double y, double z){
parentThing= myThing;
Initialize();
// more code involving x, y, z
}
// a few more constructors
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 22
通常,最好将所有构造函数链接到包含最多信息的单个构造函数,例如
BigBlock(Thing myThing) {
this(myThing, 0, 0, 0); // Assuming 0 is the default value for x, y and z
}
Run Code Online (Sandbox Code Playgroud)
如果有不同的方式来调用构造函数而不能有效地表示相同信息的子集,那么它就会变得略微怪异- 但在那一点上我会说有一种设计气味.
请注意,当您在单个构造函数中获得所有真实逻辑时,您根本不需要您的Initialize方法(应该initialize遵循Java命名约定,顺便说一句) - 这也可能使您的字段最终成为先前的你不可能做到的.