模拟主人投喂宠物
//宠物类
public class Pet {
private String name;
private String food;
public Pet(String name, String food) {
this.name = name;
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public void eat(Pet pet){
System.out.println(pet.name+"吃"+pet.getFood());
}
}
public class Cat extends Pet{
public Cat(String name,String food) {
super(name,food);
}
@Override
public void eat(Pet pet){
System.out.println(pet.getName()+"吃"+pet.getFood());
}
}
public class Dog extends Pet{
public Dog(String name,String food) {
super(name,food);
}
@Override
public void eat(Pet pet){
System.out.println(pet.getName()+"吃"+pet.getFood());
}
}
public class Pig extends Pet{
public Pig(String name,String food) {
super(name,food);
}
@Override
public void eat(Pet pet){
System.out.println(pet.getFood()+"吃"+pet.getFood());
}
}
//主人类
public class Master {
//喂养宠物
public void feed(Pet pet){
System.out.println("给"+pet.getName()+"喂食"+pet.getFood());
pet.eat(pet);
}
}
public class TestMaster {
public static void main(String[] args) {
//创建一个主人的实例
Master master = new Master();
master.feed(new Cat("小猫咪","小鱼干"));//养猫
master.feed(new Cat("小狗狗","大骨头"));//养狗
master.feed(new Cat("小猪猪","猪饲料"));//养猪
}
}
学“废”了吗?