[英]Java issues with updating variables correctly
I have the following Account
class which is the super class of CurrentAccount
. 我有以下
Account
类,它是CurrentAccount
的超类。 I am however having issues when I create an instance of each class. 但是,当我创建每个类的实例时遇到问题。 The
currentAccount
should take away 6 as a charge if the balance is below 100 but its taking away 3. I'm obviously missing a deceleration somewhere. 如果余额低于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);
}
}
In Java, instance variables do not replace or override the same named variable in a superclass. 在Java中,实例变量不会替换或覆盖超类中的相同命名变量。 If you declare a same-named variable in a subclass, now you have two variables, not one.
如果在子类中声明同名变量,则现在有两个变量,而不是一个。 Just because you declared another
fee
in CurrentAccount
doesn't mean the code in Account
will use the fee
in CurrentAccount
-- it can't. 仅仅因为您在
CurrentAccount
中声明了另一fee
并不意味着Account
的代码将使用CurrentAccount
的fee
-不能。
To apply the different behavior you need, declare a method called getFee()
in Account
returning a double
that can be overridden in CurrentAccount
to change the behavior. 若要应用所需的其他行为,请在
Account
声明一个名为getFee()
的方法,该方法返回一个可以在CurrentAccount
覆盖的double
以更改行为。
In Account: 在帐户中:
public double getFee() { return 3.00; }
In CurrentAccount: 在CurrentAccount中:
@Override
public double getFee() { return 6.00; }
Then call getFee()
whenever you need to reference the fee, instead of referring to fee
. 然后调用
getFee()
每当你需要引用费,而不是指fee
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.