Reputation: 1
Given a Class with multiple constructors
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();
}
}
and a subclass
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 /\ /\ /\ */
}
}
What is the accepted way to include the code shared between the two broccoli constructors? It seems that my options, are either mainatain two separeate copies of the same code in the separate functions, or, create an "init()" or "construct()" function that holds the shared code once, and is called from each constructor. Are there any other options I am missing?
What is generally accepted as the cleanest way to deal with this situation (I'm looking for best practices, not opinions on what people think is best.)
Thanks
Upvotes: 0
Views: 74
Reputation: 1
You can have the code in one constructor and call it from another by using
this (parameters list);
Hopefully an if else block is enough to differentiate between different flows.
Upvotes: 0
Reputation: 394146
You can call this(param1,param2)
to invoke one constructor from the other.
Broccoli(int fibre_count, int flavor_amount, int vitamin_count){
this (fibre_count,flavor_amount,some_default_preserve,vitamin_count);
}
You should always call the constructor with more parameters from the contsructor with less parameters, and give default values to the additional parameters.
Upvotes: 3
Reputation: 1874
The best practice is to call the other constructor using this(..) but if only a few lines of code is common between two constructors then the only option I think is to implement a common method and call the method from the constructors.
Upvotes: 0