无法建立建于动物园的容器

时间:2019-07-26 00:05:19

标签: java

我正在尝试实现一个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创建了类,该类扩展到PandaElephant。 我(尝试)创建要添加动物的动物园容器。

当我运行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 ();
  }

2 个答案:

答案 0 :(得分:0)

编译器给您一个错误,因为您没有为新实例化的Zoo类分配指针。

这是不正确的:

Zoo = new Zoo();

这是正确的:

Zoo variableName = new Zoo();

然后您可以致电

variableName.addAnimal(Elle);

答案 1 :(得分:0)

您的代码看起来很接近。这里有一些建议。

  1. 修改Zoo类,使其不扩展Animal。动物园可以包含动物,但是动物园本身的定义不是某种动物。因此请将此class Zoo extends Animal更改为class Zoo。这是一个改进,您可以选择保留原样,但是您的“动物园”似乎也不是“动物”。
  2. 声明一个适当的“ zoo”变量。现在,您收到了一个编译错误,因此请将此Zoo = new Zoo();更改为类似以下内容:Zoo theZoo = new Zoo();。然后,您将有一个名为“ theZoo”的变量供以后使用。
  3. 遵循命名约定,并以小写字母开头的变量名称。代替Panda SpotElephant Elle(它们声明变量“ Spot”(大写字母“ S”)和“ Elle”(大写字母“ E”))使用小写名称:Panda spot和{ {1}}。
  4. 最后,将动物添加到您的动物园:Elephant elletheZoo.addAnimal(spot);
  5. 删除theZoo.addAnimal(elle);的重复变量。每个species都具有以下内容:Animal –它定义了一个具有包范围的String species;成员变量。 speciesElephant分别定义了以下内容: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);
    }
}