I've never needed to do this before but since both have to be the 'first' line in the constructor how should one tackle it? What's the best refactoring for a situation like this?
Here's a sample:
public class Agreement extends Postable {
public Agreement(User user, Data dataCovered)
{
super(user);
this(user,dataCovered,null);
}
public Agreement(User user,Data dataCovered, Price price)
{
super(user);
if(price!=null)
this.price = price;
this.dataCovered = dataCovered;
}
...
}
The call to super(user)
is an absolute must. How to deal with "optional parameters" in this case? The only way I can think of is repetition i.e., don't call this(...) at all. Just perform assignments in every constructor.
You cannot call both super(..) and this(...). What you can do is re-work the structure of your overloadeded constructors, so that the last one to be called will call super(...). If that is not an option, you'll have to do the assignments in every constructor.
If you call this(user,dataCovered,null)
, the second constructor will be called, and the first thing it will do is call the super constructor. So the line super(user);
in the first constructor is unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With