面向对象多态猫狗精髓代码灵活、增加动物和食物不需要改动底层方法

动物类 :

public class Animal {
    void cry() {
        System.out.println("动物都会叫....");
    }
    void eat() {
    }
}

动物的子类啊猫和啊狗

 

class Dog extends Animal{
    void cry() {
        System.out.println("小狗汪汪叫...");
    }
    
    void eat() {
        System.out.println("小狗喜欢吃......");
    }
}


class Cat extends Animal{
    void cry() {
        System.out.println("猫咪 喵喵喵叫...");
    }
    
    void eat() {
        System.out.println("小猫喜欢吃......");
    }
}

 

 

食物类:

 

/**
 * 食物类
 * @author lsh
 *
 */
public class Foot {

    public void showName() {
        System.out.println("食物");
    }
}

 

食物类的子类猫粮狗粮

class Fish extends Foot{
    public void showName() {
        System.out.println("鱼");
    }
}

class Bone extends Foot{
    public void showName() {
        System.out.println("骨头");
    }
}

 

 

 

主人类:

class Master{
    //主人喂食物的方法 给出动物 和食物
    void feed(Animal an,Foot foot) {
        an.eat();
        foot.showName();
    }
}

 

测试:

public class TestAnimal {

    public static void main(String[] args) {
        // 实现多态的 三个必要条件 : 继承 、 重写  、父类引用执行子类对象
        Animal an = new Dog();
        an.cry();
        an = new Cat();
        an.cry();
        System.out.println("==============================");
        
        //创建一个主人类
        Master m = new Master();
        m.feed(new Dog(),new Bone());
        m.feed(new Cat(),new Fish());
    }
}

 

测试结果:

小狗汪汪叫...
猫咪 喵喵喵叫...
==============================
小狗喜欢吃......
骨头
小猫喜欢吃......

 

总结:

多态:多种形态,代码灵活,精髓在于高度管理。中央集权制。

java中允许父类的引用变量引用它的子类的实例,多态的必要基础之一,多态不管怎么实现,关键一点在于类型自动转换。

 

 

欢迎拍砖。。。。。。。。。。。。。。

 

posted @ 2018-05-06 10:43  马鞍山  阅读(299)  评论(0)    收藏  举报