Mowjah
Mowjah

Reputation: 7

How to use switch statement that involves instantiation in cases?

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

Answers (1)

Elliott Frisch
Elliott Frisch

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

Related Questions