Search code examples
javainitializervariable-initializationinitialization-block

Why does encasing variable initialization into an initialization block allow initialization before declaration?


Consider the following code:

class New {
    id = 2;
    int id = 7;
}

Obviously it won't compile as we attempt to initialize an undeclared variable.

Encasing the statement into an initialization block, however, makes it compile successfully:

class New {
    { id = 2; }
    int id = 7;
}

What is this "feature" of an initialization block that makes this initialization before declaration valid?

Before asking the question I read several posts on initialization blocks on SO, but they seem to mostly address issues on the order of initialization (e.g. static vs non-static).


Solution

  • The point is that id = 2; is a statement, which can be put in an initializer block.

    Your first code is not illegal because of the declaration order, but because you cannot use statements out of code blocks. This one fails too:

    class New {      
        int id = 7;
        id = 2;
    }
    

    Declaration of instance variables can appear anywhere in the class. Has nothing to do with initializer blocks at all.

    For example, your code is equivalent to

    class New {
        New() { id = 2; }
        int id = 7;
    }
    

    According to your question, this would be illegal too, because initialisation happens before declaration.

    Just get used to the convention to always declare instance variable on the beginning of the class, if that confuses you.