0

This is the class which contains all characters and objects within a level.

CollisionListener is an interface, and CollisionListener.beginContact() is called whenever a character collides with another object.

I'm wondering, since I'm passing level into CollisionListener, does this mean 2 objects are stored in memory?

Or is private Level level inside CollisionListener just a reference to original level? How is this handled internally by JVM?

Since when I modify level inside CollisionListener, the original level is updated too.

public class Level extends World {

    private Player player;
    private Enemy enemy;

    public Level(){

        this.setContactListener(
            new CollisionListener(this));

        player = new Player();
        enemy = new Enemy();
    }

    /**
     * Move characters
     */
    public update(){

        player.update();
        enemy.update();
    }
}

This is an interface, thats added to my Level object. It needs a reference to a Level object so level.doSomething() can be invoked.

public class CollisionListener implements ContactListener{

    private Level level;

    public CollisionListener(Level level){

        this.level = level;
    }

    public void beginContact(Contact contact) {

        this.level.doSomething();
    }

    /* other interface methods .. */
}
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150

1 Answers1

0

Or is private Level level inside CollisionListener just a reference to original level? How is this handled internally by JVM?

Of course it is. You always only deal with references to objects and copy those. In terms of C/C++ you could compare the references with pointers.

Since when I modify level inside CollisionListener, the original level is updated too.

If you don't want that to happen, create a copy of the Level instance, e.g. by using the Clonable interface.

Thomas
  • 87,414
  • 12
  • 119
  • 157