多态练习题(宠物医院治疗小动物的问题 ,多态的应用:向上类型传递)

package com.Summer_0427.cn;

/**
 * @author Summer
 * 宠物医院治疗小动物的问题
 * 多态的应用:向上类型传递
 *
 */
class Pet{
    private String name;
    public Pet(String name) {
        super();
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void eat(){}
}

class Dog extends Pet{

    public Dog(String name) {
        super(name);
    }
    
    public void eat(){
        System.out.println("小狗吃骨头");
    }
    
    public void run(){
        System.out.println("小狗跑了");
    }
    
}

class Cat extends Pet{

    public Cat(String name) {
        super(name);
    }
    
    public void eat(){
        System.out.println("小猫吃鱼");
    }
    
    public void play(){
        System.out.println("小猫去玩了");
    }
    
}

class Hospital{
    //看病     多态    向上类型转换       类之间的关系:依赖  局部变量
    public void treatment(Pet pet){//Pet pet = wangwang;new Dog()
        System.out.println("给:"+pet.getName()+"看病");
        pet.eat();
        //对象类型的判断
        if (pet instanceof Dog) {
            Dog dog = (Dog)pet;//把pet进行强转
            dog.run();
        } else {
            Cat cat = (Cat)pet;
            cat.play();
        }
    }
}

public class TestHospital {
    public static void main(String[] args) {
        Hospital hos = new Hospital();
        Dog p = new Dog("p");
        Cat c = new Cat("c");
        hos.treatment(p);
        hos.treatment(c);
    }
}

UML图

 

 

posted @ 2019-04-28 00:02  Geek张东坡  阅读(384)  评论(0编辑  收藏  举报