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

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);
            
        }
    }

猜你喜欢

转载自www.cnblogs.com/zhangmenghui/p/10544786.html