Java的多态

Posted on 2016-12-22 19:50  Eva·Kinsey  阅读(161)  评论(0编辑  收藏  举报

多态的定义:

      同一种行为,在不同对象上有不同的表现形式

实现多态的条件:

  • 要有继承
  • 要有方法的重写
  • 要有父类的引用指向子类的对象

代码如下:

 1 public class Animal {
 2     String name="miaomiao";
 3     
 4     /**
 5      * 叫的方法
 6      */
 7     public void shout(){
 8         System.out.println("XX动物在叫");
 9     }
10 
11 }
 1 /**
 2  * 实现Animal的多态首先继承Animal
 3  * @author Administrator
 4  *
 5  */
 6 public class Dog extends Animal{
 7     String name = "狗狗";
 8     //重写Animal的shout方法
 9     @Override
10     public void shout() {
11         System.out.println("狗狗在汪汪叫。。。");
12     }
13 
14 }
在该类中,重写了Animal中的方法
public class AnimalTest {
    public static void main(String[] args) {
        //用父类的引用指向子类的对象
        Animal d = new Dog();
        Animal a = new Animal();
        //方法取决于引用,对象取决于类型
        System.out.println(d.name);
        d.shout();
        a.shout();
    }

}