Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reference and new keyword

Tags:

java

oop

abstract

I'm writing a simple chessboard while learning Java and come up with the following question:

I have abstract class ChessPiece and classes like King, Queen, Rook etc. which all extend ChessPiece.

And I have a 2D array of ChessPiece for the chessboard.

public ChessPiece myChessBoard[][] = new ChessPiece[8][8];

Then I make my chess pieces like this:

ChessPiece aPiece = new Rook();

And put it on myChessBoard so I can find it:

myChessBoard[0][0] = aPiece;

Same goes for other pieces...

My question is when I do this public ChessPiece myChessBoard[][] = new ChessPiece[8][8]; in my first step, I used new keyword and allocated 8*8 = 64 ChessPiece objects right? But I did it again when writing ChessPiece aPiece = new Rook(); I feel stuff in myChessBoard such as myChessBoard[0][0] don't need to be allocated since it's just a reference and don't need that much space as a real chess piece like new Rook().

In short I feel I only need to allocate 32 chess pieces with new keyword (32 pieces on a chessboard) instead of 32 + 64 = 96 chess pieces.

I might have confused some basic concept in Java, please help.

Edit:

myChessBoard[][] = new ChessPiece[8][8] here I used new keyword to create 64 reference without real object. So new keyword doesn't necessarily create new objects, it can also create new references referring to null, right?

that is wrong. "the new keyword in that case is creating a new 2D array Object" thanks to accepted answer.

like image 909
Arch1tect Avatar asked Nov 18 '25 06:11

Arch1tect


1 Answers

All you're doing with this public ChessPiece myChessBoard[][] = new ChessPiece[8][8]; is initializing a new game board. The game board has 64 squares (each square represented by a 2D index value), not 64 chess pieces. So each square can be given a chess piece value like myChessBoard[0][0] = new Rook();

// or to give your pieces references
Knight blackKnight1 = new Knight();
myChessBoard[0][1] = blackKnight1;

Bishop blackBishop1 = new Bishop();
myChessBoard[0][2] = blackBishop1;

Queen blackQueen = new Queen();
myChessBoard[0][3] = blackQueen;

// and do the rest with all the other pieces according 
// to their position in the 2d array
like image 104
Paul Samsotha Avatar answered Nov 20 '25 23:11

Paul Samsotha