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图

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

 

相关文章:

  • 2021-12-05
  • 2021-07-23
  • 2022-12-23
  • 2021-12-31
  • 2021-04-29
  • 2021-09-29
  • 2021-12-31
  • 2021-06-29
猜你喜欢
  • 2022-03-07
  • 2022-12-23
  • 2022-12-23
  • 2021-04-06
  • 2022-01-31
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案