How to create a copy of an instance without having access to private variables
- by Jamie
Im having a bit of a problem. Let me show you the code first:
public class Direction {
private CircularList xSpeed, zSpeed;
private int[] dirSquare = {-1, 0, 1, 0};
public Direction(int xSpeed, int zSpeed){
this.xSpeed = new CircularList(dirSquare, xSpeed);
this.zSpeed = new CircularList(dirSquare, zSpeed);
}
public Direction(Point dirs){
this(dirs.x, dirs.y);
}
public void shiftLeft(){
xSpeed.shiftLeft();
zSpeed.shiftRight();
}
public void shiftRight(){
xSpeed.shiftRight();
zSpeed.shiftLeft();
}
public int getXSpeed(){
return this.xSpeed.currentValue();
}
public int getZSpeed(){
return this.zSpeed.currentValue();
}
}
Now lets say i have an instance of Direction:
Direction dir = new Direction(0, 0);
As you can see in the code of Direction, the arguments fed to the constructor, are passed directly to some other class. One cannot be sure if they stay the same because methods shiftRight() and shiftLeft could have been called, which changes thos numbers.
My question is, how do i create a completely new instance of Direction, that is basically copy(not by reference) of dir?
The only way i see it, is to create public methods in both CircularList(i can post the code of this class, but its not relevant) and Direction that return the variables needed to create a copy of the instance, but this solution seems really dirty since those numbers are not supposed to be touched after beeing fed to the constructor, and therefore they are private.