java 是否支持多重分派?如果不是,下面的代码是如何工作的?

Does java support multiple dispatch? If not how is the below code working?

java是否支持多重分派?如果不是,下面的代码是如何工作的?

Account.java

public interface Account 
{
    public void calculateInterest();
}

储蓄Account.java

public class SavingsAccount implements Account
{

}

贷款Account.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());        
     }
}

输出

Interest rate for Loan Account is 11.5%
Interest rate for Savings Account is 6.5%

首先是一些术语

Overloading is the ability to create multiple methods of the same name with different implementations.

在 Java 中,这是基于参数的编译时类型执行的,: 使用带有 matching signature 的方法,与参数的值无关。

Overriding allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

在Java中,这是通过根据引用对象的运行时间(动态)类型确定要调用的方法来执行的。这是Java实现single dispatch and it is not be confused with overloading的方法。

Multiple dispatch means that a function or method can be dynamically dispatched based on the run-time (dynamic) type or, in the more general case some other attribute, of more than one of its arguments.

Java是否支持多重分派?

在 Java 中,不直接支持多重分派。

但是,您可以 emulate multiple dispatch 通过结合重载使用多层单一分派。

此代码如何工作?

请注意,此代码首先需要您为 LoanAccountSavingAccount 提供 calculateInterest() 的实现,即使它不会在您的 POC 的其余部分中使用.

在您的 class InterestCalculation 中,您有三个不同的方法重载 getInterestRate()。它们每个都有不同的签名(例如参数类型)。因此 main() 将根据声明的参数类型(从构造函数推导出来)调用正确的方法。

您可以优化您对单一调度的使用并使 InterestCalculation 更加通用(例如,您可以添加更多 Account 的实现而无需更改它):

public interface Account 
{
    public void calculateInterest();
    public double getInterest(); 
    public String getType(); 
}
...
public class InterestCalculation 
{
    public void getInterestRate(Account objAccount)
    {
        System.out.print ("Interest Rate for "+objAccount.getType()+" is ");
        System.out.print (objAccount.getInterest());
        System.out.println (" %");
    }
}

Online demo