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)
Say .. you do
Player p1 = new Player(); Player p2 = new Player(); p1.setLocation(p2.getLocation());
Now an error / problem occurs when you try to change the location of others. Both player locations change in the same way, as they both now have the same location.
So, of course, this will work very well.
p1.setLocation(new Location(p2.getLocation()));
but the problem is that it always creates a new object .. when could I just update an existing instance ..? how can I update an existing default instance without doing my own methods, as I did below to fix this.
I had to fix this using the method below (any way to do this by default without doing this below)
public void setLocation(Location location) { if (this.location == null) this.location= new Location(location); else this.location.updateLocation(location); }
Does anyone know any tricks that I may not know about? Thanks.
source share