需求

编写一个程序,Master类中有一个feed(喂食)方法,可以完成主任给动物喂食物的信息。
入门案例 - 图2
image.png

Animal

  1. package test;
  2. public class Animal {
  3. private String name;
  4. public Animal(String name) {
  5. this.name = name;
  6. }
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. }

Cat

  1. package test;
  2. public class Cat extends Animal {
  3. public Cat(String name) {
  4. super(name);
  5. }
  6. }

Dog

  1. package test;
  2. public class Dog extends Animal {
  3. public Dog(String name) {
  4. super(name);
  5. }
  6. }

Pig

  1. package test;
  2. public class Pig extends Animal {
  3. public Pig(String name) {
  4. super(name);
  5. }
  6. }

Food

  1. package test;
  2. public class Food {
  3. private String name;
  4. public Food(String name) {
  5. this.name = name;
  6. }
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. }

Fish

  1. package test;
  2. public class Fish extends Food {
  3. public Fish(String name) {
  4. super(name);
  5. }
  6. }

Bone

  1. package test;
  2. public class Bone extends Food {
  3. public Bone(String name) {
  4. super(name);
  5. }
  6. }

Rice

  1. package test;
  2. public class Rice extends Food {
  3. public Rice(String name) {
  4. super(name);
  5. }
  6. }

Master

  1. package test;
  2. public class Master {
  3. private String name;
  4. public Master(String name) {
  5. this.name = name;
  6. }
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. //使用多态机制,可以统一的管理主人喂食的问题
  14. //animal 编译类型是Animal,可以指向(接收) Animal子类的对象
  15. //food 编译类型是Food ,可以指向(接收) Food子类的对象
  16. public void feed(Animal animal, Food food) {
  17. System.out.println("主人 " + name + " 给 " + animal.getName() + " 吃 " + food.getName());
  18. }
  19. //传统方法
  20. /*//主人给小狗 喂食 骨头
  21. public void feed(Dog dog, Bone bone) {
  22. System.out.println("主人 " + name + " 给 " + dog.getName() + " 吃 " + bone.getName());
  23. }
  24. //主人给 小猫喂 鱼
  25. public void feed(Cat cat, Fish fish) {//构成了方法的重载
  26. System.out.println("主人 " + name + " 给 " + cat.getName() + " 吃 " + fish.getName());
  27. }*/
  28. //问题引出:
  29. //如果动物很多,食物很多
  30. //===> feed 方法很多,不利于管理和维护
  31. }

Main

  1. package test;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Master tom = new Master("汤姆");
  5. Dog dog = new Dog("大黄~");
  6. Bone bone = new Bone("大棒骨~");
  7. tom.feed(dog, bone);
  8. Cat cat = new Cat("小花猫~");
  9. Fish fish = new Fish("黄花鱼~");
  10. System.out.println("===========-------");
  11. tom.feed(cat, fish);
  12. //添加 给小猪吃米饭
  13. Pig pig = new Pig("小花猪");
  14. Rice rice = new Rice("米饭");
  15. System.out.println("===================");
  16. tom.feed(pig, rice);
  17. }
  18. }

运行结果

image.png