繁体   English   中英

Java问题与正确更新变量

[英]Java issues with updating variables correctly

我有以下Account类,它是CurrentAccount的超类。 但是,当我创建每个类的实例时遇到问题。 如果余额低于100,那么currentAccount应该扣除6作为费用,但扣除3。我显然在某处缺少减速。

public class Account {

    private String name;
    private double balance;
    public double initDeposit;
    public double threshold = 100.00;
    public final double fee = 3.00;

    public Account(String name, double initDeposit) {
        this.balance = initDeposit;
        this.name = name;
    }

    public void deposit(double amount) {
        setBalance(amount);
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double amount) {
        balance += amount;
    }

    public void withdraw(double amount) {
        if (getBalance() < 100 && getBalance() >= -50) {
            balance = balance - amount - fee;
        } else {
            balance = balance - amount;
        }
    }

    public String toString() {
        String s = "Name: " + name + "\n" + "Balance: " + balance;
        return s;
    }
}

public class CurrentAccount extends Account {

    private String name;
    private double balance;
    public double initDeposit;
    public double threshold = 100.00;
    public final double fee = 6.00;

    public CurrentAccount(String name, double initDeposit) {
        super(name, initDeposit);
    }
}

在Java中,实例变量不会替换或覆盖超类中的相同命名变量。 如果在子类中声明同名变量,则现在有两个变量,而不是一个。 仅仅因为您在CurrentAccount中声明了另一fee并不意味着Account的代码将使用CurrentAccountfee -不能。

若要应用所需的其他行为,请在Account声明一个名为getFee()的方法,该方法返回一个可以在CurrentAccount覆盖的double以更改行为。

在帐户中:

public double getFee() { return 3.00; }

在CurrentAccount中:

@Override
public double getFee() { return 6.00; }

然后调用getFee()每当你需要引用费,而不是指fee

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM