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


    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图

     

  • 相关阅读:
    202002知识点
    爬取思想流程
    测试
    运维
    设计模式重温
    ?March2020疑问点
    最方便简洁的设置Sublime编辑预览MarkDown
    rime中州韵输入法安装及配置
    Deepin更新Sublime并取消更新提示
    关于在线教学软件一些发现和思考
  • 原文地址:https://www.cnblogs.com/summerdata/p/10781200.html
Copyright © 2020-2023  润新知