简体   繁体   English

我工厂出了什么问题?

[英]What's wrong with my factory?

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. 但Eclipse告诉我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(); 我更改了行return new FooImpl(); to return new Foo.FooImpl(); 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). 这里有 FooImpl解释 - 简而言之,你需要使类FooImpl static ,所以它只与外部类相关联,而不是外部类的特定实例 (你没有)。 The getFoo method also looks like it should be static, btw -- otherwise, what instance of Foo were you planning on calling it on? getFoo方法也看起来应该是静态的,顺便说一句-否则,什么情况下Foo是你在调用它的规划?

How do you intend people to call getFoo() ? 你打算怎么打电话给getFoo()

Unless you're doing something completely funky and radical, you'll need to make it static . 除非你做的事情完全是时髦和激进的,否则你需要让它变得static

使FooImplstatic ,它将工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM