Java 正确更新变量的问题

标签 java

我有以下 Account 类,它是 CurrentAccount 的父类(super class)。然而,当我创建每个类的实例时,我遇到了问题。如果余额低于 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 中,实例变量不会替换或覆盖父类(super class)中相同的命名变量。如果您在子类中声明一个同名变量,那么现在您有两个变量,而不是一个。只是因为你声明了另一个 feeCurrentAccount并不意味着 Account 中的代码将使用feeCurrentAccount -- 不能。

要应用您需要的不同行为,请声明一个名为 getFee() 的方法。在Account返回 double可以在 CurrentAccount 中覆盖改变行为。

帐户中:

public double getFee() { return 3.00; }

在当前帐户中:

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

然后调用getFee()每当您需要引用费用时,而不是引用fee .

关于Java 正确更新变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21686860/

相关文章:

java - 从 Java 执行 shell 命令

java - Java 中的斯坦福词性标注器

java - 如何正确关闭这些线程

用于通过网络摄像头捕获图像的java代码UnsatisfiedLinkError

java - 具有间接依赖性的 Guice 中的多个实现

java - 如何在胖客户端中设计身份验证以确保故障安全?

java - 在添加新数据之前如何清除 SQLite 表中的所有条目?

java - 无法将 Base64 字符串解码为位图

java - 如何修复 ScriptRunner 中的错误请求 - jira

java - 尝试从 Java 运行 Github CLI 命令 gh auth login --with-token 时出现问题