haxor789
haxor789

Reputation: 614

Commands in anonymous blocks inside a class of any use

If seen this question here: Instance initializer and *this* keyword

and now I ask myself is something like this:

public class Main {

    public static void main(String args[]) {    
        new Main();
    }

    { System.out.println(x); } //Error here

    int x=1;
}

of any (even just theoritical) use? I mean this part:

 { System.out.println(x); } //Error here

As far as I can say its anonymous so I'd have no idea how to execute it manually, it doesn't seem to be executed automatically is not part of any function or whatsoever. Sorry if this questions is already answered, but the ones that I found targeted {} to restrict the variable scope but in this case I could not think of a way to get into that scope or make it run.

Upvotes: 1

Views: 57

Answers (1)

Eran
Eran

Reputation: 394026

It's an instance initialization block. Whenever you create an instance of the class, it is executed before the body of the constructor you use.

Therefore the only way to execute it manually is by creating an instance of the class in which this block appears (or a sub-class of that class).

Upvotes: 1

Related Questions