多态练习题(通过UML建模语言来实现饲养员喂养动物)
项目需求如下图:
package com.Summer_0428.cn; /** * @author Summer * 1.构建一个食物抽象类,Bone和Fish分别为其实现类,通过super传参。 * 2.构建一个动物类,对于Dog类和Cat类,分别使用多态,使food父类引用实现子类方法。 * 3.构建饲养员类,分别传入Food类和Animal类,多态的应用。 * */ /**食物父类*/ abstract class Food{ private String name; public Food(String name) { this.name = name; } public String getName() { return name; } } class Bone extends Food{ public Bone(String name) { super(name); } } class Fish extends Food{ public Fish(String name) { super(name); } } /**动物父类*/ abstract class Animal{//多态 public abstract void eat(Food food); } class Dog extends Animal{ @Override public void eat(Food food) {//多态 System.out.println("小狗吃"+food.getName()); } } class Cat extends Animal{//多态 @Override public void eat(Food food) { System.out.println("小猫吃"+food.getName()); } } class Feeder{ public void feed(Food food,Animal animal){//多态 System.out.println("饲养员喂养"); animal.eat(food); } } public class TestFeeder { public static void main(String[] args) { Bone bone = new Bone("骨头"); Fish fish = new Fish("鱼"); Dog dog = new Dog(); Cat cat = new Cat(); Feeder Tom = new Feeder(); Tom.feed(bone, dog); Tom.feed(fish, cat); } }