我有一些名為“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”中的所有其他常規方法“ 班級。我該如何解決這個問題?
uj5u.com熱心網友回復:
Java 是一種靜態型別語言。如果您有一個型別為 的變數Account,則只能呼叫Account(及其超類和實作的介面)中定義的方法。嘗試呼叫未定義的方法Account將導致編譯時錯誤,因為就編譯器而言,變數中保存的值只是一個Account.
因此,編譯器不允許您呼叫 的方法TaxDeduction,然后Account(或其超類之一)必須實作它,或者您必須檢查變數持有的實體是否是TaxDeduction(使用instanceof)的實體,然后強制轉換為TaxDeduction和呼叫方法。
當您使用instanceof時,您會在運行時檢查實際型別,并且強制轉換告訴編譯器您確定它實際上是 a 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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314639.html
上一篇:無法從派生型別串列訪問擴展方法
