I’ve got some code where I have a variable that requires a lengthy class declaration. I’d like to define the variable at the top of the page, then define it later like so:
private IFoo bar;
/* seemingly irrelevant code */
bar = new IFoo() { /* a bunch of stuff */ };
But my Java compiler complains that this can’t happen. It says there’s a syntax error on a } on the line before (this really doesn’t make sense because it IS in its proper place).
So to quiet the compiler, I’ve put the definition of my variable inside more { }
. I forget what this pattern is called, but I know why it exists and shouldn’t really be necessary in my case.
{
bar = new IFoo() { /* a bunch of stuff */ };
}
Anyway, I guess my question is, why can’t I just do
bar = new IFoo(){}; and not
{ bar = new IFoo(){}; }
?
Other details: IFoo is an interface, I’m using JDK 1.6 with Android and Eclipse.
Defining bar immediately works just fine:
private IFoo bar = new IFoo() { /* stuff */ };
The reason it does not work is that Java does not allow free-standing code. You must put your code inside a method, a constructor, or an initializer.
This is an initializer:
This is a declaration followed by an assignment:
You can do this kind of stuff in a function, if your
baris a local variable (you’d need to dropprivatethen). But in the class declaration it is not allowed.Adding curly braces around the assignment makes your code part of the constructor, where assignments are allowed again. That’s why the following assignment worked: