重写CheckingAccount类withdraw方法时遇错误求助
问题分析与解决方案
看起来你在编写CheckingAccount的取款方法时踩了两个常见的子类继承坑:无限递归和构造方法未初始化父类属性,我来帮你梳理并修正:
1. 核心问题:无限递归调用
你的withdraw方法里,当判断符合透支条件后调用的withdraw(money),其实是在反复调用当前CheckingAccount类自己的withdraw方法,而不是父类Account的取款逻辑,这会直接导致栈溢出错误。
2. 次要问题:构造方法未初始化父类属性
Account类的id和balance是私有属性,子类无法直接访问,你的CheckingAccount构造方法没有调用父类构造方法,会导致父类的属性无法正确初始化。
修正后的完整代码
class CheckingAccount extends Account { double overdraftmax = -50; // 调用父类构造方法初始化id和balance public CheckingAccount(int id, double balance) { super(id, balance); } public void withdraw(double money) { // 检查是否在允许的透支范围内 if (this.getBalance() - money >= overdraftmax) { // 明确调用父类的withdraw方法执行实际取款操作 super.withdraw(money); } // 可选:添加透支超限的处理逻辑,比如抛出异常 // else { // throw new IllegalArgumentException("取款金额超出透支上限"); // } } } class Account { private int id = 0; private double balance = 0; // 父类构造方法,用于初始化私有属性 public Account(int id, double balance) { this.id = id; this.balance = balance; } // 父类的取款核心逻辑 public void withdraw(double money) { // 可以添加基础校验,比如取款金额不能为负 if (money > 0) { this.balance -= money; } } // 对外提供余额访问方法 public double getBalance() { return this.balance; } }
关键修正说明
- 用
super.withdraw(money)替代withdraw(money),明确指定调用父类的取款实现,彻底避免递归循环。 - 在
CheckingAccount构造方法中添加super(id, balance),让父类完成私有属性的初始化。 - 建议在else分支添加透支超限的处理逻辑,比如抛出异常,让代码的错误处理更健壮。
内容的提问来源于stack exchange,提问作者tcann99
相关产品推荐
相关产品推荐

