Note that there are some explanatory texts on larger screens.

plurals
  1. POJava reference and new keyword
    primarykey
    data
    text
    <p>I'm writing a simple chessboard while learning Java and come up with the following question:</p> <p>I have abstract class <code>ChessPiece</code> and classes like <code>King</code>, <code>Queen</code>, <code>Rook</code> etc. which all extend <code>ChessPiece</code>.</p> <p>And I have a 2D array of ChessPiece for the chessboard.</p> <pre><code>public ChessPiece myChessBoard[][] = new ChessPiece[8][8]; </code></pre> <p>Then I make my chess pieces like this:</p> <pre><code>ChessPiece aPiece = new Rook(); </code></pre> <p>And put it on myChessBoard so I can find it:</p> <pre><code>myChessBoard[0][0] = aPiece; </code></pre> <p>Same goes for other pieces...</p> <p>My question is when I do this <code>public ChessPiece myChessBoard[][] = new ChessPiece[8][8]; </code> in my first step, I used new keyword and allocated 8*8 = 64 ChessPiece objects right? But I did it again when writing <code>ChessPiece aPiece = new Rook();</code> 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 <code>new Rook()</code>. </p> <p>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.</p> <p>I might have confused some basic concept in Java, please help.</p> <p>Edit:</p> <p><code>myChessBoard[][] = new ChessPiece[8][8]</code> 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? </p> <p>that is wrong. "the new keyword in that case is creating a new 2D array Object" thanks to accepted answer.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload