【发布时间】:2017-05-14 04:43:40
【问题描述】:
java 支持多分派吗?如果不是,下面的代码是如何工作的?
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());
}
}
输出
贷款账户利率为 11.5% 储蓄账户利率为 6.5%【问题讨论】:
-
这就是方法重载的工作原理。您的实际方法参数是特定的子类型,而不仅仅是
Account。 -
你是说方法重载和多重调度是一样的?
-
new LoanAccount() 和 new SavingsAccount() 都是在运行时创建的,那怎么会超载呢?
-
尝试传递
Account类型的变量,(假设稍后在运行时您将使用具体的对象引用来实例化它)。在这种情况下,将调用与 Account 作为参数对应的方法。这是您拥有的简单方法重载。当编译器看到调用了相同的方法名称时,它会看到您传递给它的参数是什么,然后它决定哪个方法具有与这些参数匹配的参数。
标签: java polymorphism multiple-dispatch