casting type in methods in java -
what wrong piece of code? consider building arraylist containing buildings , building superclass farm , stonemine:
public building returnbuilding(int i) { if(buildings.get(i) instanceof farm) return (farm)buildings.get(i); if(buildings.get(i) instanceof stonemine) return (stonemine)buildings.get(i); else return null; }
then if call
returnbuilding(1).somemethodejustinfarmclass();
which building.get(1)
instance of farm class, run time error
returnbuilding
returns building
, not farm
. casting game.buildings.get(i)
before returning not change that.
if runtime class of game.buildings.get(i)
farm
, cast return value of returnbuilding
farm
before calling somemethodejustinfarmclass
method.