先贴上代码
<pre name="code" class="java">package com.ray.object; /** * 父类引用子类对象 * * @author ray * @since 2015-04-30 * @version 1.0 * */ public class Test { class Person { public void say() { System.out.println("i am a person"); } } class Man extends Person { @Override public void say() { System.out.println("i am a man"); } } class Woman extends Person { @Override public void say() { System.out.println("i am a woman"); } } public Person getType(Person person) { return person; } public static void main(String[] args) { Person person = new Test().getType(new Test().new Person()); //好处: //1.解耦,person所对应的子类发生改变,但是下面这一句person.say();一直是不变的 //2.代码复用 person.say(); person = new Test().getType(new Test().new Man()); person.say(); person = new Test().getType(new Test().new Woman()); person.say(); } }
输出:
i am a person
i am a man
i am a woman
如果再扩展一下,我们会说到接口、说到简单工厂的设计模式,但是这里暂时不聊,等后面学到了再详细展开
原文地址:http://blog.csdn.net/raylee2007/article/details/45390093