如何重载构造函数的情况下如何调用super(...)和this(...)? [英] How to call both super(...) and this(...) in case of overloaded constructors?

查看:111
本文介绍了如何重载构造函数的情况下如何调用super(...)和this(...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有需要这样做,因为两者都必须是在构造函数中的第一行,应该如何解决呢?

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?

下面是一个示例:

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;


}
   ...
}


$ b b

super(user)的调用是绝对必须的。在这种情况下如何处理可选参数?我能想到的唯一的方法是重复,即不要调用这个(...)。只需在每个构造函数中执行分配。

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.

推荐答案

您不能同时调用super(..)和this(...)。你可以做的是重新工作你重载的构造函数的结构,所以最后一个被调用将调用super(...)。
如果这不是一个选项,你必须在每个构造函数中进行赋值。

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.

这篇关于如何重载构造函数的情况下如何调用super(...)和this(...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆