class Player
{
private Location location;
public Location getLocation()
{
return location;
}
public void setLocation(Location location)
{
this.location = location;
}
}
...
class Location
{
int x,y,z;
public Location(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Location(Location location)
{
this.x = location.x;
this.y = location.y;
this.z = location.z;
}
public void updateLocation(Location location) //the fix..
{
this.x = location.x;
this.y = location.y;
this.z = location.z;
}
}
说..你做
Player p1 = new Player();
Player p2 = new Player();
p1.setLocation(p2.getLocation());
现在,当您尝试修改其他人的位置时,就会出现错误/问题。两个玩家的位置变化完全相同,因为他们现在共享相同的位置。
所以当然,下面的这个就可以了。
p1.setLocation(new Location(p2.getLocation()));
但问题是它总是创建一个新对象..当我可以更新现有实例时..?如何在默认情况下更新现有实例,而不像下面那样创建自己的方法来解决此问题。
我必须使用下面的方法来解决这个问题(默认情况下任何方式都可以做到这一点,而不是像下面这样)
public void setLocation(Location location)
{
if (this.location == null)
this.location= new Location(location);
else
this.location.updateLocation(location);
}
有人知道我可能不知道的任何技巧吗?谢谢。