简体   繁体   中英

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. 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.

Note that neither class should extend the other, or it would be like saying Zoo extends Animal or Animal extends Zoo. A Zoo contains Animals, and a Fleet contains Boats (Ships actually).

This will work only if Boat extends from Fleet

Else you can go ahead with,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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