开发者

What's wrong with my factory?

开发者 https://www.devze.com 2022-12-13 07:27 出处:网络
I\'ve got some code like this: public abstract class Foo { public static Foo getFoo() { return new FooImpl();

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 Eclips开发者_如何学JAVAe 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();


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?


How do you intend people to call getFoo()?

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


Make the FooImpl class static and it will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消