Subclass name to be a parameter?
For my AP Computer Science project, I needed to finish a chess game by the end of the school year (till June). We are supposed to have the board ready in OO and stuff in 2 days.
I was almost done, except for putting images as pieces, which created a big mess for me. So right now, I have the following set up:
Chessboard extends Applet (The main function is here)
Chesspiece with subclasses:
- Rook
- Knight
- Bishop
- Queen
- King
- Pawn
Chessgrid, grids on the chessboard. When Chesspiece is constructed, it will be given a Chessgrid to specify its location.
Okay. I need to draw an image with g.drawImage(), however, since I can only access ImageObserver from Chessboard, I can't draw the Image in constructors of those Chesspieces. And, I want to write as less code as possible, so I decided to create such method in Chessboard:
Code:
public static Chesspiece putPiece(Chesspiece cp, int color, Chessgrid cg, Graphics g, ImageObserver o){
cp = new Pawn(color, cg, g);
int tempx = 25-cp.img.getWidth(o)/2;
int tempy = 25-cp.img.getHeight(o)/2;
g.drawImage(cp.img, cp.cg.positionx+tempx, cp.cg.positiony+tempy, o);
return cp;
}
Notice though, this is only for the class Pawn. Can I make it so that it takes in a subclass name as a parameter, and create an object of that subclass inputted? In other words, can I make it so that something like this is possible: putPiece(Rook) to instantiate a Rook and draw itself out; putPiece(Queen) to instantiate a Queen and draw itself out, etc. without creating several different methods?
Thanks.