4

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 */ };
4
  • 3
    You might want to consider creating a SSCCE. Commented Jul 22, 2012 at 2:50
  • I really spent a bit of time trying to make this question look pretty..... Commented Jul 22, 2012 at 3:16
  • A SSCCE isn't a pretty question, it's a short code sample that we can run in our IDEs to see your exact problem as you saw it. It helps us figure out your problem so we can give you a better answer faster Commented Jul 22, 2012 at 3:18
  • 1
    class c{private Object o;o=new Object();} Commented Jul 22, 2012 at 3:20

1 Answer 1

4

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 */ };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh right you are. I see now I've got some "free-standing code". I think I was just staring at the problem for too long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.