I am trying to make a copy of an object to make some tests on it without affecting the original object. I made this copy() function but the original object is still affected.
Inside the class "I" I have this copy function:
@Override
public Piece copy() {
I newPiece = new I(blocks[0], blocks[1], blocks[2], blocks[3]);
newPiece.STATUS = this.STATUS;
newPiece.FORM = this.FORM;
return newPiece;
}
and I try to make a copy like this:
Piece rotated = piece.copy();
rotated.changeForm();
Class "I" is a subclass of the abstract class Piece with the abstract method copy(). when I do the changeForm() in the copied object it affects the original one too.
SOLVED
the Block objects were passed as reference too so I needed to add a copy() method even for the type Block. Code changed this way:
@Override
public Piece copy() {
I newPiece=new I(blocks[0].copy(),blocks[1].copy(),blocks[2].copy(),blocks[3].copy());
newPiece.STATUS=this.STATUS;
newPiece.FORM=this.FORM;
return newPiece;
}