Unknown Unknown - 5 months ago 5
Java Question

Java: Move content from one variable to another

I'm currently working on a chess game using Java, and I came accross a problem. Every field of the chessboard might have a chess piece on it, which you can get by typing:

field.getPiece() //null or Piece-object

Now, when moving a Piece, I wanted to do it like this:

field2.setPiece( field1.getPiece() );
field1.setPiece( null );

The problem is, that field1 keeps the reference of the piece, and overwrites it with null, so that the Piece gets deleted. So my question is: How do I move the content / reference of a variable to another one, without pointing both variables at the same reference?

Btw: I know, that I could clone my Piece, and then delete the old one, but I hope there is a more efficient way of doing this.

Relevant code:

public class Field {
private Piece piece;

public Piece getPiece(){ return piece; }

public void setPiece(Piece piece){
this.piece = piece;
piece.setField(this); //Tell the piece on what field it is (to get position etc.) [LINE 53]

public abstract class Piece {
protected Field field;
public void setField(Field field){
this.field = field;



java.lang.NullPointerException: Attempt to invoke virtual method 'void [...].Piece.setField(Field)' on a null object reference
at [...].Field.setPiece(Field.java:53)

When removing the last line in the code (
), it works (it doesn't crash)

EDIT2: After receiving the answer, I realized, that my idea up there was fully wrong, and the error was caused by a simple problem...


Problem is with piece.setField(this); line in setPiece method. as when you set a piece null how you can call setField on null object.

so just place a null check before `piece.setField(this);.