先看下我的代码
动物抽象类
abstract class Animal {
public abstract void drink();
public abstract void move(String destination);
}
哺乳动物抽象类继承动物类
abstract class Mammal extends Animal{
//
```哺乳动物类
}
爬行动物类
abstract class Reptitel extends Animal {//爬行动物类
}
老虎类
public class Tiger extends Mammal implements Hunt{
String name = "Tiger";
public void move(String destination){
System.out.println("Tiger move to "+destination+".");
}
public void drink(){
System.out.println("Tiger have drunk.");
}
public void hunt(Animal animal){
System.out.println("Tiger has eaten "+animal);
}
public String getName() {
return name;
}
}
蛇类
public class Snake extends Reptitel implements Hunt{
String name = "Snake";
public void move(String destination){
System.out.println("Snake move to "+destination+".");
}
public void drink(){
System.out.println("Snake have drunk.");
}
public void hunt (Animal animal){
System.out.println("Snake has eaten "+animal);
}
public String getName() {
return name;
}
}
兔子类
public class Rabit extends Mammal {
String name = "Rabit";
public void move(String destination){
System.out.println("Rabit move to "+destination+".");
}
public void drink(){
System.out.println("Rabit have drunk.");
}
public String getName() {
return name;
}
}
Hunt接口
interface Hunt extends Animal{
public void hunt(Animal animal);
}
农夫类
public class Famer {
String name = "famer";
public void bringWater(String destination){
System.out.println("Famer bring a bottel of watter to "+destination);
}
public void feedWater(Animal animal,String destination){
this.bringWater(destination);
animal.move(destination);
animal.drink();
System.out.println(animal+" has been fed by famer\n");
}
public void feedWaterThreePlaces(){
Animal tiger = new Tiger();
Animal snake = new Snake();
Animal rabit = new Rabit();
Famer famer = new Famer();
famer.feedWater(tiger ,"room");
famer.feedWater(snake,"livingroom");
famer.feedWater(rabit,"river");
}
public void bringAnimal(Animal animal,String destination){
System.out.println("Famer brings "+animal+" to "+destination);
}
//这个feedAnimal我写不出来,希望大佬解答。
//我想同这个方法完成农夫给肉食性动物喂食
//1.农夫将食物带到进食房间
//2.食肉性动物移动到进食房间
//3.肉食性动物用hunt方法完成进食
public void feedAnimal(Animal food,Animal hunter){
this.bringAnimal(food,"feeding room");
hunter.move("feeding room");
//以下是我遇到的难题,我的hunter无法调用hunt方法,我觉得可能是
//因为animal中有tiger rabit snake但是只有tiger和snake拥有hunt方法
//所以hunter不能调用hunt方法
hunter.hunt(food); //这行代码被报错
}
}
Test以上方法
public class Run {
public static void main(String[] args) {
//用于执行famer的喂食方法测试
}
}