什么是单分派,什么是多分派呢???
先看定义:根据一个宗量的类型进行方法的选择称为单分派
根据多于一个宗量的类型对方法的选择称为多分派
那么宗量又是个什么东东呢?????
再看定义:方法的接受者与方法的参数统称为方法的宗量。
定义看着确实有点儿晕,还是直接上例子吧!!!!!!!!!
package test;
public class Dispatch {
static class Ipad{}
static class Iphone{}
public static class Father{
public void hardChoice(Ipad arg){
System.out.println("Father choice Ipad!!!");
}
public void hardChoice(Iphone arg){
System.out.println("Father choice Iphone!!!");
}
}
public static class Son extends Father{
public void hardChoice(Ipad arg){
System.out.println("Son choice Ipad!!!");
}
public void hardChoice(Iphone arg){
System.out.println("Son choice Iphone!!!");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Father father = new Father();
Son son = new Son();
father.hardChoice(new Ipad());
son.hardChoice(new Iphone());
}
}
输出:
Father choice Ipad!!!
Son choice Iphone!!!
下面看看编译阶段编译器的选择过程,也就是静态分派的过程。
这个时候,选择目标方法依据两点:
一个是静态类型Father和Son,
二是方法参数Ipad和Iphone。
这次选择的结果的最终产物是产生了两条invokevirtual指令,两条指令的参数分别为常量池中指向Father.hardChoice(ipad)
及Father.hardChoice(iphone)方法的符号引用。因为是根据两个宗量进行选择,所以Java语言的静态分派属于多分派类型。
再看看运行阶段虚拟机的选择,也就是动态分派的过程。
在执行son.hardChoice(new Ipad())这句代码时,由于编译期已经决定目标方法的签名必须为hardChoice(Ipad),虚拟机不会关心传递过来的参数到底是什么,因为这时参数的静态类型、实际类型都对方法的选择不会构成任何影响,唯一可以影响虚拟机选择的因素只有此方法的接受者的实际类型到底是Father还是Son。因为只有一个宗量作为选择一句,所以Java语言的动态分派属于单分派类型。