Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查子类中的值,然后将其发送到私有超类变量_Java_Inheritance - Fatal编程技术网

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);
    }
}
但一般来说,这种继承层次结构需要重新检查设计的正确性。

这将违反“子类型中的先决条件无法加强”-可能需要重新考虑您的设计。