簡體   English   中英

如何使用由 class 實現的接口方法,它還擴展了另一個 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM