Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Typecasting & Calling Methods Simultaneously

Tags:

java

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?

like image 803
nick Avatar asked Nov 29 '25 06:11

nick


1 Answers

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();
    }
like image 83
corsiKa Avatar answered Nov 30 '25 20:11

corsiKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!