本文共 1470 字,大约阅读时间需要 4 分钟。
方法静态分派演示
/** * 方法静态分派演示 * Created by tiantao on 15-2-9. */public class StaticDispatch { static abstract class Human { } static class Man extends Human { } static class Woman extends Human { } public void sayHello(Human guy) { System.out.println("hello,guy!"); } public void sayHello(Man guy) { System.out.println("hello,gentleman!"); } public void sayHello(Woman guy) { System.out.println("hello,lady!"); } public static void main(String[] args) { Human man = new Man(); Human woman = new Woman(); StaticDispatch testJVM = new StaticDispatch(); testJVM.sayHello(man); testJVM.sayHello(woman); }}执行输出:
hello,guy!
hello,guy!接下来是方法动态分派演示
/** * 方法动态分派演示 * Created by tiantao on 15-2-9. */public class DynamicDispatch { static abstract class Human { protected abstract void sayHello(); } static class Man extends Human { @Override protected void sayHello() { System.out.println("man say hello!"); } } static class Woman extends Human { @Override protected void sayHello() { System.out.println("woman say hello!"); } } public static void main(String[] args) { Human man = new Man(); Human woman = new Woman(); man.sayHello(); woman.sayHello(); }}执行输出:
man say hello!
woman say hello!本来对方法重载和方法得重写概念挺清晰得,今天看了书里的这两个例子一下被带模糊了。
对第一个例子,静态分派的结果有点小意外。加强一下记忆。
转载地址:http://ionmi.baihongyu.com/