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.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

java - How to create Table using Apache PDFBox -

mpi - Why is MPI_Bsend not returning error even when the buffer is insufficient to accommodate all the messages -