给定一个具有多个构造函数的类
class Food {
int fibre_count;
int flavour_amount;
PreservationProcess preserve;
public Food( int fibre_count, int flavour_amount){
this.fibre_count = fibre_count;
this.flavor_amount = flavor_amount;
preserve = new PreservationProcess("Freshly Picked");
/*do some other complicated thing that you do _not_ want done in
the other constructor*/
}
public Food (int fibre_count, int flavour_ammount, PreservationProcess preserve){
this.fibre_count = fibre_count;
this.flavor_amount = flavor_amount;
this.preserve = preserve;
this.flavour_amount *= preserve.getFlavourModifier();
}
}
和子类
class Broccoli extends Food {
int vitamin_count;
SomeOtherObj = SO_Obj;
int branch_count;
Broccoli(int fibre_count, int flavor_amount, int vitamin_count){
super(fibre_count, flavour_amount);
/*common code between the two constructors \/ \/ \/ */
this.vitamin_count = vitamin_count;
SO_Obj = new SomeOtherObject();
branch_count = 4;
greenness = 13;
/*common code between the two constructors /\ /\ /\ */
}
Broccoli(int fibre_count, int flavor_amount, PreservationProcess preserve, int vitamin_count){
super(fibre_count, flavour_amount, preserve);
/*common code between the two constructors \/ \/ \/ */
this.vitamin_count = vitamin_count;
SO_Obj = new SomeOtherObject();
branch_count = 4;
greenness = 13;
/*common code between the two constructors /\ /\ /\ */
}
}
包含两个西兰花构建者之间共享的代码的可接受方式是什么?似乎我的选项要么是在单独的函数中维护相同代码的两个separeate副本,要么创建一个“init()”或“construct()”函数来保存共享代码一次,并从每个构造函数调用。我还缺少其他选择吗?
普遍接受的是处理这种情况的最简洁方法(我正在寻找最佳实践,而不是人们认为最好的观点。)
由于
答案 0 :(得分:3)
您可以调用this(param1,param2)
从另一个调用一个构造函数。
Broccoli(int fibre_count, int flavor_amount, int vitamin_count){
this (fibre_count,flavor_amount,some_default_preserve,vitamin_count);
}
您应该始终使用带有较少参数的contsructor中的更多参数调用构造函数,并为其他参数提供默认值。
答案 1 :(得分:0)
最佳实践是使用this(..)调用其他构造函数,但如果两个构造函数之间只有几行代码是通用的,那么我认为唯一的选择是实现一个公共方法并从构造函数中调用该方法
答案 2 :(得分:0)
您可以将代码放在一个构造函数中,然后使用
从另一个构造函数中调用它this(参数列表);
希望if else块足以区分不同的流程。