Reputation: 7
I have an instance variable piece
that is of type Object
. It is instantiated as one of several classes in my program as a part of a switch
statement as follows:
public Object getRandomPiece() {
int random = (int)(Math.random()*8);
switch(random) {
case 0: case 1:
_piece = new Piece1();
}
return _piece;
}
Note that there are multiple cases, I have just summarized it in this snippet. My problem is that after giving _piece
its value from the switch
statement and returning it, I cannot access any of its new class's methods (example, methods from class Piece1
). How should I approach this?
Upvotes: 0
Views: 329
Reputation: 201439
Program to a common Piece
interface. If you don't use object state, prefer to make your method static
. I would prefer a ThreadLocalRandom
over Math.random()
, and I would prefer to avoid unnecessary local temporary variables. Putting that together, it might look something like
public static Piece getRandomPiece() {
switch (ThreadLocalRandom.current().nextInt(8)) {
case 0: case 1:
return new Piece1();
}
return null;
}
Upvotes: 1