{
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]);
}
}
因此,Ship类是超类,而CargoShip和CruiseShip都扩展了Ship类。我已经将3个对象存储到Ship数组中。 setCargoCapacity和setMaxPassengers是仅出现在子类中的方法。由于某些原因,我无法访问它们。我不知道如何做到这一点,以便我也可以访问子类方法。
最佳答案
您可以在将对象存储在数组中之前对其进行初始化:
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};