我有课程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;
}
还有两个类
Champion
和Spell
: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
的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
最佳答案
在gitHub中查看代码,您有2种方法:
//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;
}