views:

120

answers:

3

I've got some code like this:

public abstract class Foo {
    public static Foo getFoo() {
        return new FooImpl();
    }

    abstract void DoFoo();

    private class FooImpl extends Foo {
        public FooImpl() { }

        @Override
        void DoFoo() { }
    }
}

But Eclipse is telling me No enclosing instance of type Foo is accessible. So how can I get this to work?

I attempted to make it as simple as possible to see if it would compile:

public abstract class Foo {
    public static Foo getFoo() {
        return new FooImpl();
    }

    private static class FooImpl extends Foo {
        public FooImpl() { }
    }
}

And I still get the same error. What am I missing?

FIXED! I changed the line return new FooImpl(); to return new Foo.FooImpl();

+8  A: 

Excellent explanation here -- in brief, you need to make class FooImpl static, so it's only tied to the outer class, not to a specific instance of the outer class (which you don't have). The getFoo method also looks like it should be static, btw -- otherwise, what instance of Foo were you planning on calling it on?

Alex Martelli
I'm going to be using this in a connection factory. Basically the consumer of the package should never know the concrete class that implements the connection they ask for. Thus there will be `connect()`, `disconnect()` and so-on methods that will be abstract on the Connection class and each implementation is responsible for providing a concrete implementation.
jasonh
+2  A: 

How do you intend people to call getFoo()?

Unless you're doing something completely funky and radical, you'll need to make it static.

Anon.
+1  A: 

Make the FooImpl class static and it will work.

Suraj Chandran