码迷,mamicode.com
首页 > 其他好文 > 详细

多态用法 由于动物很多,所以创建一个人类来喂动物

时间:2019-03-16 23:16:38      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:sys   写法   package   stat   nbsp   用法   动物类   []   static   

package cn.zmh.A;

//动物类
public class Animal {
   void eat(){
       
   }
}

//猫类
 class Cat extends Animal {
    void eat(){
        System.out.println("猫吃鱼");
    }
}
 
 //狗类
 class Dog extends Animal {
        void eat(){
            System.out.println("狗吃骨头");
        }
    }

//人类   喂猫喂狗
 class Persosn extends Animal {
        void feedAnimal(Animal anim){

           //打印运行的地址
            anim.eat();
        }
    }
 
//测试类
 class TestAnimal {


        public static void main(String[] args){
           //多态写法
           Animal d = new Dog();
           Animal c = new Cat();
            
            Persosn p = new Persosn();
            
            //子类的值d赋值给父类Animal
            Animal aimn = (Animal) d;
            p.feedAnimal(aimn);
            
            //子类的值c赋值给父类Animal
            Animal aimn1 = (Animal) c;
            p.feedAnimal(aimn1);
            
        }
    }

多态用法 由于动物很多,所以创建一个人类来喂动物

标签:sys   写法   package   stat   nbsp   用法   动物类   []   static   

原文地址:https://www.cnblogs.com/zhangmenghui/p/10544786.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!