Java – how to call super (…) and this (…) in the case of overloaded constructors?

I never needed to do this before, but since both must be the "first line" in the constructor, what should I do with it? What is the best refactoring for such a situation?

Here is an example:

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 is absolutely necessary How do I handle optional parameters in this case? The only way I can think of is repetition, that is, don't call it (...) Just execute the task in each constructor

Solution

You cannot call super (..) at the same time And this (...) What you can do is rebuild the structure of the overloaded constructor so that the last called call will call super (...) If this is not an option, you must perform an assignment in each constructor

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>