一道面试题,以下程序的输出是?
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 sd = new StaticDispatch(); sd.sayHello(man); sd.sayHello(woman); } }
hello , guy!
hello , guy!
------------------------
对于 Human man = new Man();
上面代码中的“Human”称为 变量的静态类型(static type),或者叫做外观类型。后面的Man是实际类型。
变量本身的静态类型不会被改变,而且终于的静态类型在编译期可知的。而实际类型变化的结果在执行期才可确定。
我们能够对上面的代码做些改动
public static void main(String[] args) { Human man = new Man(); Human woman = new Woman(); StaticDispatch sd = new StaticDispatch(); sd.sayHello((Man)man); sd.sayHello((Woman)woman); }
hello, gentleman!
hello, lady!