如何使用由 class 实现的接口方法也扩展了另一个 class?
How to use interface method implemented by a class which also extends another class?
我有一些 classes 命名为“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”的对象。当我在 main class 中检索“CurrentAccount”对象并尝试使用“deductTax()”方法时,我收到错误消息,指出“deductTax()”方法未在“Account”中解析,而我可以使用所有其他正常方法“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();
}
}
我有一些 classes 命名为“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”的对象。当我在 main class 中检索“CurrentAccount”对象并尝试使用“deductTax()”方法时,我收到错误消息,指出“deductTax()”方法未在“Account”中解析,而我可以使用所有其他正常方法“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();
}
}