1.静态分派-针对方法重载
package com.example.demo.dispatch;
public class StaticDispatch {
public static void main(String[] args) {
Human man = new Man() ;
Human woman = new Woman();
sayHello(man);
sayHello(woman);
}
static abstract class Human {
}
static class Man extends Human {
}
static class Woman extends Human {
}
public static void sayHello(Human human) {
System.out.println("Hi I am human");
}
public static void sayHello(Man human) {
System.out.println("Hi I am Man");
}
public static void sayHello(Woman human) {
System.out.println("Hi I am Woman");
}
}
输出结果是
Hi I am human
Hi I am human
Human是静态类型或外观类型,后面指向的Man则是实际类型。静态类型的变化仅在使用时发生,实际类型实在运行时才能确定。在重载时是根据静态类型而不是实际类型判断的
sayHello((Man) man);
sayHello((Woman) woman);
有些情况编译器无法推断出唯一的版本时,往往只能确定一个“更加适合的版本”
package com.example.demo.dispatch;
import java.io.Serializable;
public class Overload {
public static void main(String[] args) {
sayHello('a');
}
public static void sayHello(Object object) {
System.out.println("Hi I am object");
}
public static void sayHello(int object) {
System.out.println("Hi I am int");
}
public static void sayHello(long object) {
System.out.println("Hi I am long");
}
public static void sayHello(char object) {
System.out.println("Hi I am char");
}
public static void sayHello(char... object) {
System.out.println("Hi I am char");
}
public static void sayHello(Serializable object) {
System.out.println("Hi I am char");
}
}
char>int>long>float>double>serializable>可变参数
2.动态分派-针对方法重写
package com.example.demo.dispatch;
public class DynamicDispatch {
public static void main(String[] args) {
Human man = new Man() ;
Human woman = new Woman();
man.sayHello();
woman.sayHello();
man = new Woman();
man.sayHello();
}
static abstract class Human {
abstract void sayHello();
}
static class Man extends Human {
public void sayHello() {
System.out.println("Hi I am human");
}
}
static class Woman extends Human {
public void sayHello() {
System.out.println("Hi I am Woman");
}
}
}
Hi I am human
Hi I am Woman
Hi I am Woman
3.单分派和多分派
单分派:一个宗量对目标方法进行选择
多分派:多个宗量对目标方法进行选择
package com.example.demo.dispatch;
public class Dispatch {
public static void main(String[] args) {
Father father = new Father();
Father son = new Son();
father.choice(new _360());
son.choice(new QQ());
}
static class _360{}
static class QQ{}
static class Father {
public void choice(_360 args) {
System.out.println("father I am 360");
}
public void choice(QQ qq) {
System.out.println("father I am QQ");
}
}
static class Son extends Father {
public void choice(_360 args) {
System.out.println("son I am 360");
}
public void choice(QQ qq) {
System.out.println("son I am QQ");
}
}
}
father I am 360
son I am QQ
4.虚拟机动态分派实现
---来源深入理解java虚拟机
网友评论