简体   繁体   中英

Variable initializing?

I was looking at some code examples and found this

Game game = new Game("Gladiator", null, 10);
{
 game.setState(GameState.STARTING);
 game.setJoinable(true);
}
{
 game.setState(GameState.LOBBY);
 game.setJoinable(true);
}
{
 game.setState(GameState.IN_GAME);
 game.setJoinable(false);
}

I was wondering what does the

{ }

initializer means

It does nothing in the context. It is just the coding style of the person - in this case, visually shows the group of lines.

In something like below, those {} would actually do something, which defines locally separated scope (the sample code is not meaningful but shows the idea):

{
    int a = 1;
}
{
    int a = 2;
}

Is this code inside a method or is it at class level?

If it is inside a method, the braces don't really do anything, they just delimit the scope of local variables defined inside the block, but since no variables are being declared inside the blocks you posted, they are not useful at all.

If these blocks are at class level, then they are instance initializers . Instance initializers are rarely used in Java, it's better to put object initialization code in a constructor.

As Peter Pei Guo says, the curly brackets are not doing anything here. But it is worth noting some other things:

  1. They are not an initializer blocks in this context. The code shown only makes sense inside a method or constructor body. In that context, curly brackets are simply a block statement ... not an initializer block.

  2. A block statement can mean something. For example:

      public void method() { { Game game = new Game("Gladiator", null, 10); game.setState(GameState.STARTING); game.setJoinable(true); } { Game game = new Game("Fashion Model", null, 10); game.setState(GameState.STARTING); game.setJoinable(true); } } 

    The blocks in this case is providing a scope that allows us to declare the second games variable without a compilation error.

But the code in your question is not using this. It looks like the author has "a thing" about the visual appearance of his code.


So which block gets executed when?

Block statements are executed in normal statement order as the enclosing block (or method body) is executed. They are just statements, and they behave like other statements.

Instance initializer blocks are executed in order with any other field declarations / instance initializers each time an instance is created. They are executed after the explicit or implicit super constructor chain, but before the rest of the current classes constructor(s).

You haven't shown us enough context to be absolutely sure what kinds of blocks these are ... but we think you are showing us block statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM