[英]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
的代碼將使用CurrentAccount
的fee
-不能。
若要應用所需的其他行為,請在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.