简体   繁体   English

如何使用不同的类对象创建一个类的数组? 爪哇

[英]how to create an array of one class using a different classes objects? Java

I am trying to create an array of Fleet that contains Boat objects. 我正在尝试创建一个包含Boat对象的Fleet数组。 I am currently getting an error that these cannot be converted to eachother. 我目前收到一个错误,这些错误无法相互转换。

public class Fleet {
    public static void main(String[] args){
        Fleet[] boats = new Boat[args.length];
    }
}

You don't want to do this. 您不想这样做。 Fleet should contain an array of Boat, not an array of Fleet. 舰队应包含一系列战舰,而不是一系列舰队。

ie,

public class Fleet {
  private Boat[] boats;

  public Fleet(int size){
    boats = new Boat[size];
    for (Boat boat : boats) {
      boat = new Boat();
    }
  }

  public static void main(String[] args) {
    int boatCount = 10;
    Fleet fleet = new Fleet(boatCount);
  }
}

Otherwise it's like saying a Fleet is a collection of Fleet which it's not. 否则,就好像说“舰队”是不是的“舰队”集合。

Also, your main method should likely not contain this array, but rather the Fleet object should. 同样,您的main方法可能不应该包含此数组,而应该包含Fleet对象。

Note that neither class should extend the other, or it would be like saying Zoo extends Animal or Animal extends Zoo. 请注意,两个类都不应该扩展另一个,或者就像说Zoo扩展Animal或Animal扩展Zoo。 A Zoo contains Animals, and a Fleet contains Boats (Ships actually). 动物园里有动物,舰队里有船(实际上是船)。

This will work only if Boat extends from Fleet 仅当BoatFleet延伸时才有效

Else you can go ahead with, 否则你可以继续

  Fleet[] boats = new Fleet[args.length];

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

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