我有以下 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)中相同的命名变量。如果您在子类中声明一个同名变量,那么现在您有两个变量,而不是一个。只是因为你声明了另一个 fee
在CurrentAccount
并不意味着 Account
中的代码将使用fee
在CurrentAccount
-- 不能。
要应用您需要的不同行为,请声明一个名为 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/