Search code examples
javainheritancescopesubclasssuperclass

Saving variable of unknown subclass type in switch statement


I have a superclass TetrisPiece, with subclasses for each variation of the piece, i.e.

class PieceI extends TetrisPiece{
}

class PieceJ extends TetrisPiece{
}

etc...

In a different class I have a switch statement based on a random number that creates a random piece

switch(rand){
      //I
      case 1: {
       PieceI pieceI = new PieceI();
       break;
      }
      //T
      case 2: {
       PieceT pieceT = new PieceT();
       break;
      }
      etc...
      default:
       break;
}

My intention is to extract the piece that is generated from the scope of the switch statement so I can use it later on in the class.

The switch method obviously does not work because of the scope issue, and I cannot create a superclass array outside of the switch statement because I would have no ability to cast the indices due to randomization.

Any help is appreciated.


Solution

  • Create an instance of the superclass TetrisPiece, and then assign PieceT, PieceI, etc to it inside the switch statement.

    TetrisPiece piece;
    
    switch(rand){
      //I
      case 1: {
       piece = new PieceI();
       break;
      }
      //T
      case 2: {
       piece = new PieceT();
       break;
      }
      etc...
      default:
       break;
    }