Search code examples
javaarraysinheritancesubclasssuperclass

How to call subclass methods when subclass objects are stored in superclass array?


{
    Ship ships = new Ship();
    CargoShip cargoShips = new CargoShip();
    CruiseShip cruiseShips = new CruiseShip();

    Ship[] allShips = {ships, cargoShips, cruiseShips};

    allShips[0].setShipName("Boom");
    allShips[0].setYearBuilt("1900");
    allShips[1].setShipName("Bang");
    allShips[1].setCargoCapaicty(200);
    allShips[2].setShipName("Bam");
    allShips[2].setMaxPassengers(500);


    for (int i = 0; i < allShips.length; i++)
    {
        System.out.println(allShips[i]);
    }
}

So the Ship class is the super class while CargoShip and CruiseShip both extend the Ship class. I've stored the 3 objects into a Ship array. setCargoCapacity and setMaxPassengers are methods that only appear in the subclasses. For some reason I cannot access them. I can't figure out how to make it so that I can also access the subclass methods.


Solution

  • You could initialize your objects before storing them in the array:

    Ship ships = new Ship();
    ships.setShipName("Boom");
    ships.setYearBuilt("1900");
    
    CargoShip cargoShips = new CargoShip();
    cargoShips.setShipName("Bang");
    cargoShips.setCargoCapaicty(200);
    
    CruiseShip cruiseShips = new CruiseShip();
    cruiseShips.setShipName("Bam");
    cruiseShips.setMaxPassengers(500);
    
    Ship[] allShips = {ships, cargoShips, cruiseShips};