jakyforever

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1:java中多态的三要素继承,重写,父类引用指向子类对象

看下面最简单的多态例子:

public class Man {
    public static void main(String[] args) {
        Animal c = new Cat("Tom", "黑色");
        c.enjoy();
        // Dog d = new Dog("大黄", "黑色");
        // Man m = new Man("苍井空",c);
        // m.MyPetEnjoy();
    }

}

class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }

    public void enjoy() {
        System.out.println("动物叫了");
    }
}

class Cat extends Animal {
    String Color;

    public Cat(String n, String c) {
        super(n);
        Color = c;
    }

    public void enjoy() {

        System.out.println("我是" + name + "  喵喵喵。。。。。。");
    }

}

class Dog extends Animal {
    String Color;

    public Dog(String name, String color) {
        super(name);
        Color = color;
    }

    public void enjoy() {

        System.out.println("我是" + name + "  汪汪汪。。。。。。");
    }

}

 

posted on 2013-09-04 17:55  jakyforever  阅读(136)  评论(0编辑  收藏  举报