ikhebgeenaccount
ikhebgeenaccount

Reputation: 373

Objects override each other

I have the class GameObject:

public class GameObject{

    private Coordinate coordinates;

    public GameObject(){
        coordinates = new Coordinate();
    }

    public void setCoordinates(int x, int y){
        coordinates.x = x;
        coordinates.y = y;
    }

    //More methods here   
}

public class Coordinate{

    public int x, y;

    public Coordinate(){

    }

    public Coordinate(int x, int y){
        this.x = x;
        this.y = y;
    }

    public void setCoordinate(int x, int y){
        this.x = x;
        this.y = y;
    }

And two classes Champion and Spell:

public class Spell extends GameObject{
    //Some methods
}

public class Champion extends GameObject{
    //Some methods
    public Spell fireBall = new Spell();
}

And in my main class:

Champion character = new Champion();

If I call character.setCoordinates(200, 300); (just random numbers), the character goes to these exact coordinates. But the Spell fireBall also goes to (200, 300). So the coordinates in Spell are overriden by the setCoordinates(int x, int y) call to character. How is this possible?

TL;DR - Two classes from GameObject, Spell extends GameObject and Champion extends GameObject, override eachother coordinates. Why?

For full source code:
GameObject.java
Spell.java
Champion.java Coordinate.java

Upvotes: 0

Views: 190

Answers (2)

nrainer
nrainer

Reputation: 2623

In the class Spell you set the coordinates:

this.startCoordinates = startCoordinates;
setCoordinates(this.startCoordinates);

Subsequently this code

if (getCoordinates().x - startCoordinates.x < range) {

is equivalent to

if (getCoordinates().x - getCoordinates().x < range) {

because getCoordinates() references the same object as startCoordinates does. Your setter method just sets the reference, but it does not copy the object.

Upvotes: 0

dkatzel
dkatzel

Reputation: 31648

Looking at your code in gitHub you have 2 methods:

//Set the coordinates for this GameObject
public void setCoordinates(int x, int y){
    this.coordinates.x = x;
    this.coordinates.y = y;
}

public void setCoordinates(Coordinate coordinates){
    this.coordinates = coordinates;
}

If you ever use the 2nd one, then you are sharing the same instance of Coordinates so changing one will change the other

The solution is to copy the values instead

public void setCoordinates(Coordinate coordinates){
    this.coordinates.x = coordinates.x;
    this.coordinates.y = coordinates.y;
}

Upvotes: 5

Related Questions