Reputation: 3564
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 */ };
Upvotes: 4
Views: 137
Reputation: 726779
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:
private IFoo bar = new IFoo() { /* a bunch of stuff */ };
This is a declaration followed by an assignment:
private IFoo bar;
/* seemingly irrelevant code */
bar = new IFoo() { /* a bunch of stuff */ };
You can do this kind of stuff in a function, if your bar
is a local variable (you'd need to drop private
then). 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:
{
bar = new IFoo() { /* a bunch of stuff */ };
}
Upvotes: 4