Very new to Java.
I have a class called GraphicsObject and a class Bug that extends it.
I have an ArrayList that holds all GraphicsObject in it:
private ArrayList<GraphicsObject> gc = new ArrayList();
Then I have a function that gets called every frame called updateObjects().
public void updateObjects(){
for(int i = 0; i < gc.size(); i++){
if(gc.get(i).toString().equals("Bug") ){
(Bug)gc.get(i).moveNorth();
}
}
}
The typecasting fails and the moveNorth() method never gets recognized because the class GraphicsObject does not have that method, only Bug does.
Any solutions?
there's a few ways you could go about it:
The most appropriate in this case would be
for(int i = 0; i < gc.size(); i++){
if( gc.get(i) instanceof Bug ){
((Bug)(gc.get(i)).moveNorth();
}
}
Alternatively, you could add a method to graphicsObject and have Bug override it
abstract public void defaultAction();
and in Bug
@Override
public void defaultAction() {
moveNorth();
}
then in your renderer:
for(GraphicsObject go : gc){
go.defaultAction();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With