Thinking in java-24 Polymorphism 多态

来源:互联网 发布:国有企业发展 知乎 编辑:程序博客网 时间:2024/06/05 21:10

1.多态Polymorphism

多态的初衷是为了让方法的适用性更强,即:当我们写了一个方法时,可以把基类作为参数,而可以将扩展类作为其参数传入;而不是将扩展类作为参数,此时该方法的适用度就没有前者高了。
Polymorphism is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.
多态的定义:一个类的实例对象表现起来就像它是其所在继承树其他类的实例一样,通常该类表现地更像其父类。极端情况是,我们创建一个参数为Object类对象的方法,那么我们可以把任意对象传给这个函数。

2.实例Demo

stackoverflow上有该问题相关的Q&A.
这里有个interesting的例子。

public abstract class Human{    public abstract void goPee();}public class Male extends Human{    @Override    public void goPee(){        System.out.println("First, stand up...");    }}public class Female extends Human{    @Override    public void goPee(){        System.out.println("First, sit down...");    }}public class TestPoly{    public static void main(String[] args){        ArrayList<Human> list = new ArrayList<>();        list.add(new Male());        list.add(new Female());        for(Human human: list)            human.goPee();    }}