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 */ };
class c{private Object o;o=new Object();}