Java子类方法修改父类属性后值无法保留的问题求助
问题分析与解决:Java子类withdraw方法修改余额不生效
问题根源
你的DebitCard类的withdraw方法中,只是定义了一个**局部变量currentAmount**来存储扣除后的余额数值,但并没有将这个值同步到父类BaseAccount的私有属性currentAmount中。父类的currentAmount是私有变量,只能通过setCurrentAmount()方法修改,你现在的操作只是在方法内部计算了一个临时值,完全没有改变对象的实际余额状态。
解决方法
在withdraw方法计算出扣除后的新余额后,调用父类提供的setCurrentAmount()方法,将新余额赋值给对象的currentAmount属性,这样后续调用balance()方法时就能读取到更新后的余额。
修改后的代码
修正后的DebitCard类
public class DebitCard extends BaseAccount{ public DebitCard(double opening, double currentAmount, double amount) { super(opening, currentAmount, amount); } public String withdraw(double amount) { double newBalance = getCurrentAmount() - amount; // 调用set方法更新父类的currentAmount属性 setCurrentAmount(newBalance); return amount + " have been retired. \nBalance: " + newBalance; } }
完整运行代码
public class BaseAccount { private double opening; private double currentAmount = 0.0; private double amount; public BaseAccount(double opening, double currentAmount, double amount) { this.opening = opening; this.currentAmount = currentAmount; this.amount = amount; } public double getOpening() { return opening; } public void setOpening(double opening) { this.opening = opening; } public double getCurrentAmount() { return currentAmount; } public void setCurrentAmount(double currentAmount) { this.currentAmount = currentAmount; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String opening(double opening) { this.opening = opening; this.currentAmount = currentAmount + opening; return "This account has been opened with " + this.opening; } public String deposit(double amount) { this.currentAmount += amount; return "Depositing " + amount; } public String balance() { return "Balance: " + currentAmount; } } public class DebitCard extends BaseAccount{ public DebitCard(double opening, double currentAmount, double amount) { super(opening, currentAmount, amount); } public String withdraw(double amount) { double newBalance = getCurrentAmount() - amount; setCurrentAmount(newBalance); return amount + " have been retired. \nBalance: " + newBalance; } } public class Inheritance { public static void main(String[] args) { BaseAccount base1 = new BaseAccount(0,0,0); System.out.println(base1.opening(500)); System.out.println(base1.deposit(22.22)); System.out.println(base1.balance()); DebitCard debit1 = new DebitCard(0,0,0); System.out.println(debit1.opening(400)); System.out.println(debit1.deposit(33.33)); System.out.println(debit1.balance()); System.out.println(debit1.withdraw(33.33)); System.out.println(debit1.balance()); } }
修改后运行结果
This account has been opened with 500.0 Depositing 22.22 Balance: 522.22 This account has been opened with 400.0 Depositing 33.33 Balance: 433.33 33.33 have been retired. Balance: 400.0 Balance: 400.0
可以看到最后一次balance()输出已经正确显示更新后的余额。
内容的提问来源于stack exchange,提问作者noobdinocoder
相关产品推荐
相关产品推荐

