java的多态特性

来源:互联网 发布:video 知乎 编辑:程序博客网 时间:2024/06/04 19:02

本篇博文的主要内容都是在java编程思想一书上看到的,在这,我只是做了总结和记录,只是为了总结自己的收获加深印象。

多态的主要作用是,改善代码的组织结构和可读性,还能够创建可扩展的程序。消除类型之间的耦合关系。

以鸟为例:

public class Bird {    public  void fly(){        System.out.println("I am a bird,i will flay");    }    private  void eat(){//只有public的方法才会被覆盖        System.out.println("I am a bird,I like eatting the worms");    }}class Dove extends Bird{    public void fly(){        System.out.println("I am a Dove,i will flay");    }    public void eat(){        System.out.println("I am a Dove,I like eatting the worms");    }}class Eagle extends Bird{    public void fly(){        System.out.println("I am a Eagle,i will flay");    }    public void eat(){        System.out.println("I am a Eagle,I like eatting the worms");    }}class Sparrow extends Bird{    public void fly(){        System.out.println("I am a Sparrow,i will flay");    }    public void eat(){        System.out.println("I am a Sparrow,I like eatting the worms");    }}class Animal{    public static void fly(Bird bird){        bird.fly();    }    public static void flyAll(Bird[] birds){        for (Bird bird:birds){            fly(bird);        }    }    public static void main(String[] args){        Bird[] birds={                new Dove(),                new Eagle(),                new Sparrow()        };        flyAll(birds);    }}
输出结果:
I am a Dove,i will flay
I am a Eagle,i will flay
I am a Sparrow,i will flay

因为有继承关系,可以很容易的将类型向上转化,用子类fly方法去覆盖父类fly方法。这么使用的要求是子类父类的方法名要相同。如果不相同,则不覆盖,调用的只是父类自己的方法。同时,子类的其他扩展方法不能以此形式调用,需要类型向下转换,才能调用。具体如下:

class DownType{    public static void main(String[] args){        Bird bird=new Bird();        Bird dove=new Dove();        bird.fly();        dove.fly();        dove=(Dove)dove;        ((Dove) dove).deliverLetters();        bird=(Dove)bird;//会报错        ((Dove) bird).deliverLetters();    }}
public class Bird {    public  void fly(){        System.out.println("I am a bird,i will flay");    }    private  void eat(){//只有public的方法才会被覆盖        System.out.println("I am a bird,I like eatting the worms");    }     public static void main(String[] args){        Bird bird=new Dove();        bird.eat();     }}class Dove extends Bird{    public void fly(){        System.out.println("I am a Dove,i will flay");    }    public void eat(){        System.out.println("I am a Dove,I like eatting the worms");    }    public void deliverLetters(){        System.out.println("I am a dove,i can deliver the letters");    }}

向下转化有要求,不是所有的对象都能转化。

静态方法是不具备多态性的。没有被public修饰的方法也不具备多态性。

原创粉丝点击