需求
编写一个程序,Master类中有一个feed(喂食)方法,可以完成主任给动物喂食物的信息。
Animal
package test;
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Cat
package test;
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
}
Dog
package test;
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
}
Pig
package test;
public class Pig extends Animal {
public Pig(String name) {
super(name);
}
}
Food
package test;
public class Food {
private String name;
public Food(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Fish
package test;
public class Fish extends Food {
public Fish(String name) {
super(name);
}
}
Bone
package test;
public class Bone extends Food {
public Bone(String name) {
super(name);
}
}
Rice
package test;
public class Rice extends Food {
public Rice(String name) {
super(name);
}
}
Master
package test;
public class Master {
private String name;
public Master(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//使用多态机制,可以统一的管理主人喂食的问题
//animal 编译类型是Animal,可以指向(接收) Animal子类的对象
//food 编译类型是Food ,可以指向(接收) Food子类的对象
public void feed(Animal animal, Food food) {
System.out.println("主人 " + name + " 给 " + animal.getName() + " 吃 " + food.getName());
}
//传统方法
/*//主人给小狗 喂食 骨头
public void feed(Dog dog, Bone bone) {
System.out.println("主人 " + name + " 给 " + dog.getName() + " 吃 " + bone.getName());
}
//主人给 小猫喂 鱼
public void feed(Cat cat, Fish fish) {//构成了方法的重载
System.out.println("主人 " + name + " 给 " + cat.getName() + " 吃 " + fish.getName());
}*/
//问题引出:
//如果动物很多,食物很多
//===> feed 方法很多,不利于管理和维护
}
Main
package test;
public class Main {
public static void main(String[] args) {
Master tom = new Master("汤姆");
Dog dog = new Dog("大黄~");
Bone bone = new Bone("大棒骨~");
tom.feed(dog, bone);
Cat cat = new Cat("小花猫~");
Fish fish = new Fish("黄花鱼~");
System.out.println("===========-------");
tom.feed(cat, fish);
//添加 给小猪吃米饭
Pig pig = new Pig("小花猪");
Rice rice = new Rice("米饭");
System.out.println("===================");
tom.feed(pig, rice);
}
}