gpt4 book ai didi

Java - 使用条件语句在 super 方法中指定参数

转载 作者:行者123 更新时间:2023-11-29 03:05:31 24 4
gpt4 key购买 nike

我有一个从另一个类扩展而来的参数化方法。抽象类 Account 是父类,SavingsAccount 继承了它的构造函数。此构造函数是参数化构造函数。我想使用条件允许(或禁止)某些值进入双 init_balance 字段,然后为父构造函数调用 super() 。

if(init_balance < minimumBalance){
//Print message to user asking for larger deposit. (is this enough to do?)
}

但是 java 语言要求我首先将对父构造函数的调用放在子构造函数中。所以我无法通过子构造函数过滤进入父构造函数的内容。

这是我在 gist 上的代码

最佳答案

如果你想保留基于构造函数的对象创建,你可以想出这个:

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;
}
}

然而 - 查看您的示例,我可能会选择在构造函数外部进行验证。

关于Java - 使用条件语句在 super 方法中指定参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32409141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com