对象互相覆盖

时间:2014-12-18 19:14:00

标签: java object extends

我有班级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;
    }

两个班级ChampionSpell

public class Spell extends GameObject{
    //Some methods
}

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

在我的main课程中:

Champion character = new Champion();

如果我拨打character.setCoordinates(200, 300);(只是随机数字),则该字符会转到这些确切的坐标。但Spell fireBall也转到(200, 300)。因此,对coordinates的{​​{1}}调用会覆盖Spell中的setCoordinates(int x, int y)。这怎么可能?

TL; DR - 来自characterGameObjectSpell extends GameObject的两个班级会互相覆盖Champion extends GameObject。为什么呢?

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

2 个答案:

答案 0 :(得分: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;
}

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

解决方案是复制值

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

答案 1 :(得分:0)

在班级Spell中设置坐标:

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

随后这段代码

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

相当于

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

因为getCoordinates()引用与startCoordinates相同的对象。 你的setter方法只是设置引用,但它不会复制对象。