我正在做继承方面的作业,到目前为止我已经创建了一个父类(super class)和一个子类。在这些类中,添加了一些方法来定义动物的名称或年龄等信息。现在我被要求执行以下操作:
- 创建一个 Demo 类,其 main 方法创建 Animal 对象的 ArrayList。在列表中填写不同的动物,以及不同的名称和年龄。
我对此完全困惑。如果我尝试在新的 ArrayList 中创建动物,它会告诉我 Animal 类是抽象的,无法实例化。以下是相关类的内容:
动物类(父类(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;
}
狼类(子类)
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);
}
}
演示类(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);
}
}
显然我应该根据这些先前的类在演示类中创建一个动物数组?我不明白这是如何完成的以及为什么我需要创建另一个主要方法。任何有关我如何编写演示类的帮助将不胜感激,因为我对我被要求做的事情感到困惑,谢谢。
演示类(class)
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));
}
我是一名优秀的程序员,十分优秀!