Java 使用构造函数创建对象

Java 使用构造函数创建对象,java,constructor,Java,Constructor,我创建了一个名为“Animal”的类,如下所示: class Animal{ int eyes,legs; } class Monkey extends Animal { int hands; Monkey(){ super.eyes=2; super.legs=2; hands=2; } } class squirell extends Animal{ int hands; int hands; Squirrel(){ super.eyes=2; super

我创建了一个名为“Animal”的类,如下所示:

class Animal{
int eyes,legs;
}
 class Monkey extends Animal
 {
 int hands;
 Monkey(){
 super.eyes=2;
 super.legs=2;
 hands=2;
 }
 }

  class squirell extends Animal{
 int hands;
 int hands;
 Squirrel(){
 super.eyes=2;
 super.legs=2;
 hands=2;
 }
 }


 class piegon extends Animal{

 int wings;
piegon(){
super.eyes=2;
super.legs=2;
wings=2;
}
}


class eagle extends Animal{

int wings;
eagle(){
super.eyes=2;
super.legs=2;
wings=2;
}
}   
我还有四个类将继承Animal类,如下所示:

class Animal{
int eyes,legs;
}
 class Monkey extends Animal
 {
 int hands;
 Monkey(){
 super.eyes=2;
 super.legs=2;
 hands=2;
 }
 }

  class squirell extends Animal{
 int hands;
 int hands;
 Squirrel(){
 super.eyes=2;
 super.legs=2;
 hands=2;
 }
 }


 class piegon extends Animal{

 int wings;
piegon(){
super.eyes=2;
super.legs=2;
wings=2;
}
}


class eagle extends Animal{

int wings;
eagle(){
super.eyes=2;
super.legs=2;
wings=2;
}
}   
我有一个使用“包含”关系的梯形图类。。梯子“包含”猴子、鹰、皮耶贡等

在这里,我想创建梯子对象,我想“放置”在梯子上的各种动物


我想使用Ladder类的构造函数创建各种动物对象。我该怎么做??有人能帮我吗?

我不太确定您的全部目标是什么,但为了将这些对象“放置”到您的梯子上,您可能需要以下内容:

class Ladder {
  private List<Animal> animalsOnLadder = new ArrayList<Animal>;

  public Ladder() {
    placeAnimalOnLadder(new eagle());
    placeAnimalOnLadder(new squirell());

  }

  public void placeAnimalOnLadder(Animal animal) {
    animalsOnLadder.add(animal);
  }

}
类阶梯{
私有列表animalsonadder=新的ArrayList;
公共阶梯(){
placeAnimalOnLadder(new eagle());
placeAnimalOnLadder(新squirell());
}
公共场所动物(动物){
动物加法器。添加(动物);
}
}
等等

不过,您可能希望将“动物”的范围置于构造函数之外:

Squirrel s; Pigeon p;
class Ladder {
    s = new Squirrel();
    p = new Pigeon();
}

用Zack的class
placeAnimalOnLadder
placeAnimalOnLadder(p)
@Eric是的,但这似乎只是一个关于在构造函数中创建其他对象的家庭作业问题。至少,这是我猜测的可能是的,但我不认为在构造函数中创建对象并不能访问它们有什么意义。所以除非提供getter方法…@Eric参见第二个示例。可通过getter方法或myLadder.s访问