繁体   English   中英

使用构造函数创建对象

[英]creating object using constructor

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

class Animal{
int eyes,legs;
}

我还有四个类将继承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;
}
}   

而且我有使用“包含”关系的梯子类。梯子“包含”猴子,鹰,皮贡等。

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

我想使用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);
  }

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

等等...

您可能会想将“动物”的范围放在构造函数之外:

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