Search code examples
javaconstructorsuperclass

How to call both super(...) and this(...) in case of overloaded constructors?


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.


Solution

  • 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.