我正在尝试实现一个Zoo
类,它将容纳您的Animals
(熊猫和大象)。在此类中,您应该具有Animal
对象的列表或数组,并且该容器应能够容纳至少5个动物
您的Zoo
类还应该具有一个函数void addAnimal(Animal a)
,该函数可让您将动物添加到动物园容器中。这些Animal
对象应该是子类的实例,并且此函数不应返回任何内容。
现在您已经拥有了所有对象,是时候编写main()
函数来测试它们了。制作一个ZooBuilder
类,其中包含一个main()
函数,该函数创建一个Zoo
和五个Animals
,然后将Animals
添加到Zoo
中。一切都很好,但还没有给您任何有用的输出。
因此,扩展您的Animal
类以使用方法void printInfo()
在同一行上打印出Animal
的名称,种类和年龄。因此,例如,如果您有一个名为“ Spot”的Panda
,它已经使用了10年,则printInfo()
函数应输出类似于以下内容的输出:
我为Animal
创建了类,该类扩展到Panda
和Elephant
。
我(尝试)创建要添加动物的动物园容器。
当我运行Zoobuilder
类和main
函数时,返回值为:
“线程“主”中的异常” java.lang.Error:未解决的编译问题: Zoo无法解析为变量”
import java.util.ArrayList;
public class Animal {
String name;
String species;
int age;
public Animal () {}
public Animal (String name, String species, int age){
this.name = name;
this.species = species;
this.age = age;
}
}
public class Elephant extends Animal {
public String species;
public Elephant () {
}
public Elephant (String name, String species, int age){
super (name, species, age);
this.name = "Elle";
this.species = "Elephant";
}
}
public class Panda extends Animal {
public String species;
public Panda () {}
public Panda (String name, String species, int age){
super (name, species, age);
this.name = "Spot";
this.species="Panda";
}
}
public class Zoo extends Animal {
public ArrayList<Animal> animals = new ArrayList<Animal>();
public void addAnimal(Animal a)
{
animals.add(a);
}
void printAllInfo()
public class Zoobuilder {
public static void main(String[] args) {
// TODO Auto-generated method stub
Zoo = new Zoo();
Panda Spot = new Panda ("Spot", "Panda", 0);
Elephant Elle = new Elephant ("Elle", "Elephant", 0);
new Animal ();
new Animal ();
new Animal ();
}
答案 0 :(得分:0)
编译器给您一个错误,因为您没有为新实例化的Zoo类分配指针。
这是不正确的:
Zoo = new Zoo();
这是正确的:
Zoo variableName = new Zoo();
然后您可以致电
variableName.addAnimal(Elle);
答案 1 :(得分:0)
您的代码看起来很接近。这里有一些建议。
Zoo
类,使其不扩展Animal
。动物园可以包含动物,但是动物园本身的定义不是某种动物。因此请将此class Zoo extends Animal
更改为class Zoo
。这是一个改进,您可以选择保留原样,但是您的“动物园”似乎也不是“动物”。Zoo = new Zoo();
更改为类似以下内容:Zoo theZoo = new Zoo();
。然后,您将有一个名为“ theZoo”的变量供以后使用。Panda Spot
和Elephant Elle
(它们声明变量“ Spot”(大写字母“ S”)和“ Elle”(大写字母“ E”))使用小写名称:Panda spot
和{ {1}}。Elephant elle
和theZoo.addAnimal(spot);
theZoo.addAnimal(elle);
的重复变量。每个species
都具有以下内容:Animal
–它定义了一个具有包范围的String species;
成员变量。 species
和Elephant
分别定义了以下内容:Panda
–定义了另一个具有公共作用域的public String species
成员变量。关于这一点,可以肯定地说,但是还有一些修正代码的建议:在species
上保留一个species
变量,然后删除其他变量。作为最后一点的示例,这里是定义新的Animal
类所需的全部操作(请注意,Cat
上没有定义任何成员变量–不需要它们,因为它可以来自Cat
)
Animal
这是一些代码来创建一只猫并打印它的名字:
class Cat extends Animal {
public Cat(String name, String species, int age) {
super(name, species, age);
}
}