简体   繁体   English

使用构造函数创建对象

[英]creating object using constructor

I've a created a class called "Animal" as shown below: 我创建了一个名为“动物”的类,如下所示:

class Animal{
int eyes,legs;
}

I've four more class which will inherit Animal class as shown below: 我还有四个类将继承Animal类,如下所示:

 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;
}
}   

And I've Ladder class which uses "contains" relationship.. Ladder "contains" Monkey,Eagle,Piegon etc.. 而且我有使用“包含”关系的梯子类。梯子“包含”猴子,鹰,皮贡等。

Here I want to create ladder object and I want to "place" various animals on ladder. 在这里,我想创建梯子对象,然后将各种动物“放置”在梯子上。

I wanted to create various animal objects using constructor of Ladder class. 我想使用Ladder类的构造函数创建各种动物对象。 How can I do that?? 我怎样才能做到这一点?? Can anyone help me.? 谁能帮我。?

I'm not quite sure what your complete goal is, but in order to "Place" these objects onto your ladder, you might want something like: 我不太确定您的完整目标是什么,但是为了将这些对象“放置”到梯子上,您可能需要类似以下内容:

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);
  }

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

etc... 等等...

You'll probably want to put the scope of the "animals" outside of the constructor though: 您可能会想将“动物”的范围放在构造函数之外:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM