Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 570
PhD Avatar asked Aug 06 '11 08:08

PhD


2 Answers

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.

like image 87
S.L. Barth Avatar answered Nov 15 '22 14:11

S.L. Barth


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.

like image 39
JB Nizet Avatar answered Nov 15 '22 13:11

JB Nizet