Home Articles

如何向包含继承的ArrayLists添加属性?

Asked
Viewed 1765 times
1

我正在做一个关于继承的任务,到目前为止我已经创建了一个超类的子类 . 在这些类中,已经添加了一些方法来定义信息,例如动物的名字或年龄 . 现在我被要求做以下事情:

  • 使用main方法创建一个Demo类,该方法创建Animal对象的ArrayList . 在列表中填入不同的动物,也有不同的名字和年龄 .

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

Animal class (super class)

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;


}

Wolf class (sub class)

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);
}
}

Demo class

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类中创建一个动物数组?我不明白这是怎么做的,为什么我还需要创建另一个主要方法 . 关于如何编写Demo类的任何帮助都会非常感激,因为我对我被要求做的事情感到困惑,谢谢 .

1 Answer

  • 0

    演示课

    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));
    
    }
    

Related