This is actually a pretty important question.
if (gameType == 'p') PigGame game = new PigGame(); else SnakeGame game = new SnakeGame();
does not compile just because of the Java grammar, which states that the variable declaration is not statemant. In fact, you can imagine code in which it actually does not need this βgameβ variable and just wants to run the constructors in the if statement.
if (gameType == 'p') new PigGame(); else new SnakeGame();
and this will compile
if (gameType == 'p'){ PigGame game = new PigGame(); }else{ SnakeGame game = new SnakeGame(); }
it will also compile
Naturally, in both cases - we do not have access to the variable outside the brackets, but nevertheless, so that the user can not encode it as
if (gameType == 'p') PigGame game = new PigGame(); else SnakeGame game = new SnakeGame();
is a little arbitrary, and AFAIK aims to make sure that the user knows what he is doing. In the general case, the evaluation of a variable is determined by its declaration around the brackets, so if you write
{ Integer x=3; System.out.println(x); //this works } System.out.println(x); //but this does not
and the same thing applies: you can declare a Game object inside an if statement, but cannot be taken outside of it by a Game variable. But it depends on your code. You might have something like
public class Game{ public static Game lastCreatedGame; public Game(){ lastCreatedGame=this; } }
then by running
if (gameType == 'p') new PigGame(); else new SnakeGame();
still give you access to the game, in the field Game.lastCreatedGame