[英]Extending a class with multiple constructors having differing behavior
给定一个具有多个构造函数的类
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 /\ /\ /\ */
}
}
包含两个西兰花构造函数之间共享的代码的可接受方式是什么? 看来,我的选择要么是在单独的函数中维护同一代码的两个单独副本,要么创建一个“ init()”或“ construct()”函数,该函数仅保存一次共享代码,并从每个构造函数中调用。 我还有其他选择吗?
通常被认为是处理这种情况的最干净的方法(我正在寻找最佳实践,而不是人们认为最好的观点。)
谢谢
您可以调用this(param1,param2)
从另一个调用一个构造函数。
Broccoli(int fibre_count, int flavor_amount, int vitamin_count){
this (fibre_count,flavor_amount,some_default_preserve,vitamin_count);
}
您应该始终从构造函数调用带有较少参数的更多参数的构造函数,并将默认值赋予其他参数。
最佳实践是使用this(..)调用另一个构造函数,但是如果两个构造函数之间只有几行代码是通用的,那么我认为唯一的选择是实现一个通用方法并从构造函数中调用该方法。
您可以将代码包含在一个构造函数中,然后使用
此(参数列表);
希望if else块足以区分不同的流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.