I have some classes named as "Account", "CurrentAccount", "SavingsAccount". "CurrentAccount" and "SavingsAccount" extends "Account", Also "CurrentAccount" implements an interface "TaxDeduction". "TaxDeduction" has method by name of "deductTax()", whose body is defined in "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();
}
Now I made an array of Account[] which stores objects of "CurrentAccount" & "SavingsAccount". When I retrieve a "CurrentAccount" Object in main class and try to use "deductTax()" method then I get error that "deductTax()" method is not resolved in "Account" whereas I can use all other normal methods in "CurrentAccount" class. How can I resolve this issue?
CodePudding user response:
If you have a variable of type Account
, you can only call methods defined in Account
(and its superclasses and implemented interfaces). If you want to call methods of TaxDeduction
, then either Account
(or one of its superclasses) must implement it, or you must check if the instance held by the variable is an instance of TaxDeduction
(using instanceof
), and then cast to TaxDeduction
and call the method.
In other words, something like:
Account[] accounts = ...;
for (Account account : accounts) {
if (account instanceof TaxDeduction) {
((TaxDeduction) account).deductTax();
}
}
Or in Java 16 and higher (JEP 394):
Account[] accounts = ...;
for (Account account : accounts) {
if (account instanceof TaxDeduction td) {
td.deductTax();
}
}