我正在进行继承任务,到目前为止我已经创建了一个超类的子类。在这些类中,已经添加了一些方法来定义信息,例如动物的名字或年龄。现在我被要求做以下事情:
我对此完全感到困惑。如果我尝试在我的新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课程的任何帮助都会非常感激,因为我对我被要求做的事情感到困惑,谢谢。
答案 0 :(得分:0)
演示课
func didBegin(_ contact: SKPhysicsContact) {}