Does java support multiple dispatch? If not how is the below code working?
Account.java
public interface Account
{
public void calculateInterest();
}
SavingsAccount.java
public class SavingsAccount implements Account
{
}
LoanAccount.java
public class LoanAccount implements Account
{
}
InterestCalculation.java
public class InterestCalculation
{
public void getInterestRate(Account objAccount)
{
System.out.println("Interest Rate Calculation for Accounts");
}
public void getInterestRate(LoanAccount loanAccount)
{
System.out.println("Interest rate for Loan Account is 11.5%");
}
public void getInterestRate(SavingsAccount savingAccount)
{
System.out.println("Interest rate for Savings Account is 6.5%");
}
}
CalculateInterest.java
public class CalculateInterest
{
public static void main(String[] args)
{
InterestCalculation objIntCal = new InterestCalculation();
objIntCal.getInterestRate(new LoanAccount());
objIntCal.getInterestRate(new SavingsAccount());
}
}
Output
Interest rate for Loan Account is 11.5% Interest rate for Savings Account is 6.5%
Account.Account, (assuming later at run time you will instansiate it with concrete object reference). In this case your method corresponding to Account as parameter will be invoked. It is simple method overloading you are having. When compiler sees same method name being invoked then it sees what is the argument you are passing in it and then it decides which method has matching parameters for those arguments.