【发布时间】:2011-10-21 09:19:29
【问题描述】:
我以前从来不需要这样做,但是由于两者都必须是构造函数中的“第一”行,应该如何处理它?对于这种情况,最好的重构是什么?
这是一个示例:
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;
}
...
}
拨打super(user) 是绝对必须的。在这种情况下如何处理“可选参数”?我能想到的唯一方法是重复,即根本不要调用 this(...) 。只需在每个构造函数中执行赋值。
【问题讨论】:
-
第一种方法不需要
super(user),直接调用this(user,dataCovered,null)即可 -
最简单的肯定是根本不提供第一个构造函数,如果它需要做的所有事情都包含在第二个构造函数中。只需记录
Price可以传递 null。
标签: java constructor superclass