java复习

2020-06-20多态

2020-06-21  本文已影响0人  智障猿

多态

使用多态的例子

public class Animal {
    public void eat(){
        System.out.println("吃食物");
    }
}
public class Cat extends Animal{
    @Override
    public void eat() {
        System.out.println("猫吃鱼!");
    }
    public void play(){
        System.out.println("玩游戏");
    }
}
public class Dog extends Animal{
    @Override
    public void eat() {
        System.out.println("狗吃骨头!");
    }
}
public class AnimalOperator {
    public void operator(Animal animal){
        //传入cat对象时相当于Animal animal = new Cat();
        //传入dog对象时相当于Animal animal = new Dog();
        animal.eat();//编译看左边,执行看右边
        //animal.play()
    }
}
public class Demo {
    public static void main(String[] args) {
        AnimalOperator animalOperator = new AnimalOperator();
        Cat cat = new Cat();
        animalOperator.operator(cat);
        Dog dog = new Dog();
        animalOperator.operator(dog);
    }
}
猫吃鱼!
狗吃骨头!

多态的转型

上一篇下一篇

猜你喜欢

热点阅读