我有一个从另一个类扩展的参数化方法。抽象类帐户是父类,SavingsAccount从它继承构造函数。此构造函数是参数化构造函数。我想使用一个条件来允许(或不允许)某些值进入double init_balance字段,然后该字段将调用父构造函数的super()。
if(init_balance < minimumBalance){
//Print message to user asking for larger deposit. (is this enough to do?)
}
但是java语言要求我首先将对父构造函数的调用放在子构造函数中。因此,我不能通过子构造函数过滤父构造函数中的内容。
这是我在要旨上的代码
发布于 2015-09-04 21:11:48
如果您想要保持基于构造函数的对象创建,可以提出以下内容:
public class SavingsAccount extends Account {
private SavingsAccount(String init_id, double init_balance)
{
super(init_id, validate(init_balance));
}
public static double validate(double init_balance) {
if (init_balance < minimumSavings) {
System.out.println("Message");
throw new RuntimeException("Message"); // or handle this error
}
return init_balance;
}
}
然而-看看您的示例,我可能会选择在构造函数之外进行验证。
发布于 2015-09-04 19:26:34
我相信这是正确的答案:为什么这个()和超级()必须是构造函数中的第一个语句?
但基本上你需要把super(init_id, init_balance);
放在第一位。
发布于 2015-09-04 20:26:56
正如其他人所说的,该语言要求您首先调用超类构造函数(我认为这是为了避免子类构造函数在初始化超类字段或方法之前访问超类字段或方法时可能出现的问题)。通常情况下,这不是一个问题,除了浪费几纳秒。如果这真的是一个问题--如果违反了约束,超类构造函数会做一些您不想做的事情--使子类构造函数私有,并使用工厂方法:
class SavingsAccount extends Account {
private SavingsAccount(String init_id, double init_balance)
{
super(init_id, init_balance);
}
public static SavingsAccount newSavingsAccount(String init_id, double init_balance) {
if (init_balance < minimumSavings) {
System.out.println("Sorry, but you need to give us moar moneyz!");
throw new Exception("Not enough money.");
}
return new SavingsAccount(init_id, double init_balance);
}
}
在剩下的代码中,您不能再说new SavingsAccount(id, balance)
;您必须说SavingsAccount.newSavingsAccount(id, balance)
。但这个价格可能是值得的,取决于你的需求。
https://stackoverflow.com/questions/32409141
复制相似问题