我正在对继承进行分配,到目前为止,我已经将超类创建为子类。在这些类中,添加了一些方法来定义信息,例如动物的名字或年龄。现在,要求我执行以下操作:


使用主方法创建一个Demo类,该方法创建一个Animal对象的ArrayList。用不同的动物,以及不同的名称和年龄填写列表。


我对此完全感到困惑。如果我尝试在新的ArrayList中创建动物,它将告诉我Animal类是抽象的,无法实例化。以下是相关类的内容:

动物类(超级类)

abstract public class Animal
{

    int age;
    String name;
    String noise;

Animal(String name, int age)
{
    this.age = age;
    this.name = name;
}

Animal()
{

  this("newborn", 0);
}

abstract public void makeNoise();

public String getName() {
        return name;
    }
  public int getAge()
    {
        return age;
    }

    public void setName(String newName) {
        name = newName;
    }

abstract public Food eat(Food x) throws Exception;

abstract public void eat(Food food, int count) throws Exception;


}


狼类(子类)

import java.util.ArrayList;

public class Wolf extends Carnivore
{

            ArrayList<Food> foodGroup = new ArrayList<>();
String name;
int age;

Wolf(String name, int age)
{
    this.name = name;
    this.age = age;
}
Wolf()
{
  super();
}
    public void makeNoise()
    {
        noise = "Woof!";
    }
    public String getNoise()
    {
        return noise;
    }

    public Food eat(Food x) throws Exception
    {
        if (x instanceof Meat) {
                return x;
            } else {
               throw new Exception("Carnivores only eat meat!");
            }
    }
public void eat(Food food, int count) {
    while (count > 0) {
        addFood(food);
        count--;
    }
}


public void addFood(Food inFood)
{
  foodGroup.add(inFood);
}
}


示范课

import java.util.ArrayList;

public class Demo {

    public static void main(String[] args)
    {
                    ArrayList<Animal> animalGroup = new ArrayList<>();
     //Add new Animals with properties such as name and age?
     Animal wolf1 = new Wolf();

    addAnimal(new Wolf("lnb1g16", 6));

    }

    public static void addAnimal(Animal inAnimal)
{
    animalGroup.add(inAnimal);
}

}


显然,我想根据这些先前的类在Demo类中创建一组Animals?我不知道该怎么做以及为什么我也需要创建另一个主要方法。非常感谢我对如何编写Demo类的任何帮助,因为我对我被要求做的事情感到困惑,谢谢。

最佳答案

示范课

public static void main(String[] args)
{
                ArrayList<Animal> animalGroup = new ArrayList<>();
 //Add new Animals with properties such as name and age?
 Animal wolf1 = new Wolf();

animalGroup.add(new Wolf("sam", 5));
animalGroup.add(new Wolf("george", 5));
animalGroup.add(new Wolf("patrick", 7));

}

07-28 06:04