![](/img/trans.png)
[英]A POJO class which extends Serializable Interface is also called as POJO class?
[英]How to use interface method implemented by a class which also extends another class?
我有一些名为“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”的对象。 当我在主 class 中检索到“CurrentAccount”Object 并尝试使用“deductTax()”方法时,出现错误“deductTax()”方法未在“帐户”中解析,而我可以在“CurrentAccount”中使用所有其他常规方法" class。我该如何解决这个问题?
Java 是一种静态类型语言。 如果您有一个Account
类型的变量,则只能调用在Account
(及其超类和实现的接口)中定义的方法。 尝试调用未在Account
中定义的方法将导致编译时错误,因为就编译器而言,变量中保存的值只是一个Account
。
因此,编译器将不允许您调用TaxDeduction
的方法,然后Account
(或其超类之一)必须实现它,或者您必须检查变量持有的实例是否是TaxDeduction
的实例(使用instanceof
),并且然后转换为TaxDeduction
并调用该方法。
当您使用instanceof
时,您会在运行时检查实际类型,并且强制转换告诉编译器您确定它实际上是一个TaxDeduction
,因此您可以调用TaxDeduction
中定义的方法。 当您对转换中的类型有误时,您将得到运行时异常ClassCastException
(这就是为什么建议在转换前使用instanceof
)。
换句话说,类似于:
Account[] accounts = ...;
for (Account account : accounts) {
if (account instanceof TaxDeduction) {
((TaxDeduction) account).deductTax();
}
}
或者在 Java 16 及更高版本( JEP 394 )中:
Account[] accounts = ...;
for (Account account : accounts) {
if (account instanceof TaxDeduction td) {
td.deductTax();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.