简体   繁体   中英

Troubles with making an array of objects

I was asked to make a fleet of tractors in a class through using an array and I keep getting errors when I try to create an array of objects.

Is this the right way to go about doing so and the rest of my code in wrong in the other classes or if I'm just not using the correct way to make an array of objects?

package testTractor;
class TestFleet {

  public static void main(String[] args) { 

      Tractor tractor = new Tractor();
      Loader loader = new Loader();
      Harvester harvester = new Harvester();

      Tractor[] fleet = new Tractor[3];

      fleet[0] = new tractor();

      fleet[1] = new loader();

      fleet[2] = new harvester();


}

  }
  1. When you define array, you give it a type:

    Tractor[] fleet = new Tractor[3];

    You will have an array of 3 elements of type Tractor . That's why you receive an error when you try to add element of type Loader . You can add just one type ( point 3 ).

  2. When you try to add the elements:

    fleet[0] = new tractor();

    This is wrong - the casing - this way you refer to a varible, not to the class. You can't instanciate from a varible ( at least no like this ). If you change the casing you will refer to the class Tractor :

    fleet[0] = new Tractor();

  3. Basic OOP - in order all of this to work like I suppose you intend, add a class Vehicle . Every class that extends Vehicle, will be a vehicle, so could be safely added to your array:

    class Vehicle{}

    and extend it all of the other classes:

    public class Tractor extends Vehicle { ... }

This way you could add more 'vehicles' like 'Car', 'Truck' or whatever ...

In the end:

Vehicle[] fleet = new Vehicle[3];
fleet[0] = new Tractor();
fleet[1] = new Loader();
fleet[2] = new Harvester();

Try with:

Tractor[] fleet = new Tractor[3];
fleet[0] = tractor;
fleet[1] = loader;
fleet[2] = harvester;

PS Edited (use Object[] if Loader and Harvester do not extend Tractor)

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