【发布时间】:2021-11-19 01:46:02
【问题描述】:
我有一些名为“Account”、“CurrentAccount”、“SavingsAccount”的类。 “CurrentAccount”和“SavingsAccount”扩展了“Account”,“CurrentAccount”也实现了“TaxDeduction”接口。 "TaxDeduction" 具有名称为 "deductTax()" 的方法,其主体在 "CurrentAccount" 中定义。
public class CurrentAccount extends Account implements TaxDeduction {
public void deductTax() {
double tax = (super.getBalance() * taxRate) / 100;
super.setBalance(super.getBalance() - tax);
}
}
public interface TaxDeduction {
static double taxRate=8.5;
void deductTax();
}
现在我创建了一个 Account[] 数组,其中存储了“CurrentAccount”和“SavingsAccount”的对象。当我在主类中检索“CurrentAccount”对象并尝试使用“deductTax()”方法时,我得到错误“deductTax()”方法未在“Account”中解析,而我可以在“CurrentAccount”中使用所有其他正常方法“ 班级。我该如何解决这个问题?
【问题讨论】:
-
使用 instanceof 和 cast。或者保留一个单独的扣除清单。
-
@daniu 我是java新手,刚开始学,没看懂你说的什么意思,能否详细说明一下?
-
@MarkRotteveel 我可以调用所有其他子类和超类方法,但问题仅在于实现接口中的抽象方法“deductTax()”。
标签: java inheritance methods interface