Thinking in Java——第八章-多态

来源:互联网 发布:杭州师范大学知乎 编辑:程序博客网 时间:2024/05/17 07:54

多态也称作动态绑定、后期绑定或运行时绑定
多态的必要条件
1、父类引用指向子类对象(向上转型)【动态绑定,这也是多态的好处,避免耦合】
2、继承
3、子类重写父类方法

向上转型

class Shape{}class Circle extends Shape{}class C{    public static void main(String[] args){        Shape shape = new Circle();//这就是向上转型,我想要一个形状,你给我一个圆,这当然可以。    }}

从下面这个例子来体会多态的必要条件

  • 父类引用指向子类对象:test函数的参数列表
  • 继承:Circle继承Shape
  • 重写:draw()被重写
class Shape(){    public void draw(){        System.out.println("Shape.draw()");    }}class Circle extends Shape{    //重写父类的方法    public void draw(){        System.out.println("Circle.draw()");    }}class Triangle extends Shape{    //重写父类的方法    public void draw(){        System.out.println("Triangle.draw()");    }}class text{    public void test(Shape shape/*动态绑定*/){        shape.draw();    }    public static void main(String[] args){        Circle c = new Circle();        Triangle t = new Triangle();        test(c);//动态绑定        test(t);//动态绑定    }}/*OutputCircle.draw()Triangle.draw()*/多态为什么好,就是因为有了动态绑定,如果没有动态绑定,要想利用test函数来写,可能就得这样:
public void test(Circle circle)[    circle.draw();}public void test(Triangle triangle){    triangle.draw();}

不但代码量增加,如果你再添加一个继承Shape的类,还需要再修改代码(再加一个test()。
看懂了这个代码再多看看有关于多态的代码。就可以理解多态了。

2 0