instances of a class

I need to create multiple instances of a class ( ship). I would like to name the new instances of the ship class "ship[some number]" so that if i needed 4 instances i could create a for loop with the result being:

ship[0]
ship[1]
ship[2]
ship[3]

I tried doing this:
private ship ship[]=null;

ship[1]=new ship();

however this doesnt work.

Am I doing it wrong, or is there just not possible

thanks



Answer this question

instances of a class

  • Alex cai

    Let's say that the class is called Ship (with capital S) to avoid confusion with variable names. You need to create an array of Ship objects:

    // declare the array

    private Ship[] ships = null;

    // initialize the array in some member function, for example the constructor

    ships = new Ship[4];

    ships[0] = new Ship();

    ships[1] = new Ship();

    ships[2] = new Ship();

    ships[3] = new Ship();

     

     

    or you can keep it short if you want

    private Ship[] shipd = new Ship[] { new Ship(), new Ship(), new Ship(), new Ship() };

     


  • Shobha69358

    just to add to that list:

    private Ship[] ships = null;

    // initialize the array in some member function, for example the constructor

    ships = new Ship[4];

    for (int counter = 0; counter < ships.Length; counter++)

    {

    ships[counter] = new Ship();

    }



  • instances of a class