简体   繁体   中英

abstract classes and polymorphism

I am creating a chess game, and I'm trying to populate my gameboard with "dummy" pieces, I've created a subclass that extends from the superclass Piece. The subclass is called Dummy. Anyways I am trying to create an instance of it by

 Piece[][] pieces=new Dummy();

The constructor in the dummy class does nothing as does the graphics2d paint method. However I am getting an error while compiling. It says "incompatible types pieces = new Dummy(); required: Piece[][] found: Dummy"

But since this is a subclass of Piece isn this declaration allowed?

Don't assign a Dummy directly to the array. Create the array first, then assign the Dummy to one of the elements of the array.

Piece[][] pieces = new Piece[8][8];
pieces[0][0] = new Dummy();  // or whichever element you want

You are trying to assign some value in a two dimensional without assign its size, which is illegal.
You must have to create the array first assigning its size, then you can assign its value individually.
You may do that:

Piece[][] pieces = new Piece[8][];
pieces[0] = new dummy[8];
pieces[1] = new dummy[8];

Hopefully the answer may help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM