求解..........

编写描述动物世界关系的继承关系程序。例如动物( Animal )包括山羊( Goat )和狼( Wolf ),山羊与狼吃( eat )的行为不同,山羊吃草,狼吃肉,但走路的( walk )的行为一致。通过继承实现以上的需求,并编写 Main 测试类,验证一群动物,其中包括狼和羊,他们吃的行为,体会多态。使用数组初始化10只动物,包括狼和羊

如有帮助望采纳。点击我回答右上角的【采纳】按钮。

public class Animal {
    public String name;
    public void walk(){
        System.out.println("走路。。。");
    }
}


public class Goat extends Animal{
    public Goat(String name) {
        this.name=name;
    }
    public void eat(){
        System.out.println(name+":山羊吃草");
    }
}


public class Wolf extends Animal{
    public Wolf(String name) {
        this.name=name;
    }
    public void eat(){
        System.out.println(name+":狼吃肉");
    }
}



public class Test {
    public static void main(String[] agrs) {
        //初始化10只动物
        Animal[] animals={new Goat("羊1"),new Wolf("狼1"),new Wolf("狼2"),new Wolf("狼3"),new Goat("羊2")
                ,new Wolf("狼4"), new Goat("羊3"),new Wolf("狼5"),new Goat("羊4"),new Wolf("狼6")
        };
        for (Animal animal :animals) {
            if (animal instanceof Goat){
                Goat goat=(Goat) animal;
                goat.eat();
            }else if (animal instanceof  Wolf){
                Wolf wolf=(Wolf) animal;
                wolf.eat();
            }
        }
    }
}

public class WorldTest {
public static void main(String[] args) {
Rabbit r=new Rabbit();
r.eat();
r.sleep();
Tiger t=new Tiger();
t.eat();
t.sleep();
}
}
class Animal{
public void eat(){
System.out.println("动物都需要吃饭");
}
public void sleep(){
System.out.println("动物都需要睡觉");
}
}
class Rabbit extends Animal{
public void eat(){
System.out.println("兔子吃草");
}
public void sleep(){
super.sleep();
}
}
class Tiger extends Animal{
public void eat(){
System.out.println("老虎吃肉");
}
public void sleep(){
super.sleep();
}
}

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632