{
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.
You can't call setCargoCapacity
of a Ship
you picked out of a Ship[]
because that ship might not be a CargoShip
. You must either provide some method in the Ship
class (and therefore for all Ships) that does what you need it to do, or check whether ship instanceof CargoShip
, and if so you can cast it ( CargoShip cargoShip = (CargoShip)ship
) and call the setCargoCapacity
of that.
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};
You cant do it. In java reference variables have two types: reference type and actual object type. So, when you write something like Object o = "12345"
, o
has type Object
(not String
), and you cant work with o
like with string without typecasting: o = ((String)o).substring(1);
.
In your case all references in your array allShips
have type Ship
. If you know that actual type of some array element is a Ship
subclass, you can cast actual type like above. But it's a bad practice and shouldn't be used in real world.
allShips[0].setShipName("Boom");
allShips[0].setYearBuilt("1900");
allShips[1].setShipName("Bang");
((CargoShip)allShips[1]).setCargoCapaicty(200);
allShips[2].setShipName("Bam");
((CruiseShip)allShips[2]).setMaxPassengers(500);
try this. It will work.
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.