对象互相覆盖

ikh*_*unt 0 java extends object

我上课了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;
    }
Run Code Online (Sandbox Code Playgroud)

和两个类Champion和Spell:

public class Spell extends GameObject{
    //Some methods
}

public class Champion extends GameObject{
    //Some methods
    public Spell fireBall = new Spell();
}
Run Code Online (Sandbox Code Playgroud)

在我的main班上:

Champion character = new Champion();

如果我打电话character.setCoordinates(200, 300);(只是随机数字),角色会转到这些确切的坐标.但Spell fireBall也是如此(200, 300).所以coordinatesin Spell被setCoordinates(int x, int y)调用覆盖character.这怎么可能?

TL; DR - 来自的两个类GameObject,Spell extends GameObject并且Champion extends GameObject互相覆盖coordinates.为什么?

完整源代码:
GameObject.java
Spell.java
Champion.java Coordinate.java

dka*_*zel 5

在gitHub中查看代码,您有两种方法:

//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;
}
Run Code Online (Sandbox Code Playgroud)

如果您使用第二个,那么您将共享相同的坐标实例,因此更改一个将更改另一个

解决方案是复制值

public void setCoordinates(Coordinate coordinates){
    this.coordinates.x = coordinates.x;
    this.coordinates.y = coordinates.y;
}
Run Code Online (Sandbox Code Playgroud)