No enclosing instance is in scope with double brace initializers

72 Views Asked by At

I have some classes nested one in another

public abstract class I
{
    public abstract int f();
}

public class J
{
    private List<I> li;
    public J(List<I> l)
    {
        li = l;
    }
}

public class A // first class
{
    private int x; // field of A
    public class B extends J // second class
    {
        public B()
        {
            super(new ArrayList<I>() // super call
            {{ // array initializer
                add(new I() // third class
                {
                    @Override
                    public int f()
                    {
                        return x; // <- here!!!
                    }
                });
            }});
        }
    }
 }

Under these conditions, I get the error: "error: no enclosing instance of type A is in scope". Removing any element from this setup fixes this error. Also, taking x and saving it to another variable then using that variable also works.

What is happening here? It seems like a bug in a compiler for me.

2

There are 2 best solutions below

1
Orr Levinger On

It is not allowed to have 2 public classes in one Java File and file name should be same as public class name.

0
OldCurmudgeon On

To experiment with your code I made a new Test class like this. I see no errors reported (using Java 8). Perhaps this is a build issue.

public class Test {

    public abstract class I {

        public abstract int f();
    }

    public class J {

        private List<I> li;

        public J(List<I> l) {
            li = l;
        }
    }

    public class A // first class
    {

        private int x; // field of A

        public class B extends J // second class
        {

            public B() {
                super(new ArrayList<I>() // super call
                {
                    { // array initializer
                        add(new I() // third class
                        {
                            @Override
                            public int f() {
                                return x; // <- here!!!
                            }
                        });
                    }
                });
            }
        }
    }

    public void test() {
        System.out.println("Hello");
    }

    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc="test">
        try {
            new Test().test();
        } catch (Throwable t) {
            t.printStackTrace(System.err);
        }
        //</editor-fold>
    }
}

Java 7 also seems to accept this code.