Java 检查子类中的值,然后将其发送到私有超类变量
在发送给超类之前,我需要检查在子类中接收到的变量量的值 这是我为我的超类所做的Java 检查子类中的值,然后将其发送到私有超类变量,java,inheritance,Java,Inheritance,在发送给超类之前,我需要检查在子类中接收到的变量量的值 这是我为我的超类所做的 //superclass public class Account { private double balance; public Account( double amount ) { balance = amount; } public Account() { this(0.0); } publ
//superclass
public class Account
{
private double balance;
public Account( double amount )
{
balance = amount;
}
public Account()
{
this(0.0);
}
public void deposit( double amount )
{
balance += amount;
}
public void withdraw( double amount )
{
balance -= amount;
}
public double getBalance()
{
return balance;
}
}
这就是我为我的子类所做的
public class SafeAccount extends Account
{
public SafeAccount(double amount)
{
// something to check if amount is positive before sending it to
super
// if it's not positive, use no argument constructor to set balance ==
0.0
}
}
我想我应该用“this(amount)”来检查它,但我不确定它是如何工作的。super()
简单的解决方法:
public class SafeAccount extends Account
{
public SafeAccount(double amount)
{
super(Math.max(0.0, amount));
}
}
如果确实必须使用无参数构造函数,则更复杂的解决方法是:
public class Account {
Account() {
}
Account(double x) {
}
}
public class SafeAccount extends Account {
private SafeAccount() {
}
private SafeAccount(double amount) {
super(amount);
}
public static SafeAccount boo(double x) {
if (x < 0.0) {
return new SafeAccount();
}
return new SafeAccount(x);
}
}
公共类帐户{
账户(){
}
账户(双x){
}
}
公共类安全帐户扩展帐户{
私人保险帐户(){
}
私人保险账户(双倍金额){
超级(金额);
}
公共静态安全帐户boo(双x){
if(x<0.0){
返回新的安全帐户();
}
返回新的安全帐户(x);
}
}
在子类中使用private
构造函数来防止构造函数实例化,并提供一个工厂方法来执行所需的检查。您可以使用以下语句
class SafeAccount extends Account {
public SafeAccount(int balance) {
super(balance > 0? balance: 0);
}
}
但一般来说,这种继承层次结构需要重新检查设计的正确性。这将违反“子类型中的先决条件无法加强”-可能需要重新考虑您的设计。