Sierox
Sierox

Reputation: 459

Creating and adding Objects (with abstract methods) to "ArrayList"s from a method

I am trying to create a basic Snake game. I have a very basic 2D Java Game Engine.Here is how all the Update's and Rendering happen:

I have an ArrayList of GameObjects which is a class I created and has two abstract methods called "update" and "render" (And also some variables which have nothing to do with the question but telling it may decrease confusion when answering it). I create objects inside the game class like in the example code below and then add these to the ArrayList. Then I basically use an enhanced for loop to update and render all the objects in the ArrayList.

I basically want to create an object in a method while the game is running (A body part will be created everytime a "food" is eaten).

When I use the following code to create a body part inside a method, I get an error for each variable I use in the "render" part saying

Cannot refer to a non-final variable body inside an inner class defined in a different method

GameObject body = new GameObject(DOT_SIZE, DOT_SIZE, food.boardPosX, food.boardPosY) {

    @Override
    void update() { 
    //MOVE PART
    }

    @Override
    void render(Graphics g) {
        g.fillRect(body.pixelPosX, body.pixelPosY, body.pixelSizeX, body.pixelSizeY);
    }
};

Also If I don't put anything into the rendering method and basically leave everything empty and try to add this "head" to the ArrayList of GameObjects in the same method I get the java.util.ConcurrentModificationException exception.

Further information:

EDIT - More Information:

The question is:

Thanks for your consideration.

Upvotes: 0

Views: 271

Answers (1)

Haifeng Zhang
Haifeng Zhang

Reputation: 31905

When I make body final, I get an error saying The local variable
body may not have been initialized.  

When you declare a variable as final, you have to assign it a value right away, or assign a value in the constructor, or you will get an error.

I suggest you to separate the GameObject with Graphics, modify Graphics object after GameObject object has been initialized at least.

For GameObject, implements render() and update in a child class(Body), you can invoke it each time your body object is created. For example, make your GameObject class as an abstract class, keep those two methods abstract, create class Body to extends from GameObject and implements them.

Based on the following code you provided,

    void render(Graphics g) {
        g.fillRect(body.pixelPosX, body.pixelPosY, body.pixelSizeX, body.pixelSizeY);
    }

I guess you wanna something like this :

    void render(Graphics g) {
                g.fillRect(this.pixelPosX, this.pixelPosY, this.pixelSizeX, this.pixelSizeY);
   }

You tried to assign values of current object to pass into fillRect

Upvotes: 1

Related Questions