是什么导致错误“无法访问 Foo 类型的封闭实例"?我该如何解决?

2022-01-30 00:00:00 java inner-classes

我有以下代码:

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}

我知道 Thing 什么都不做,但是没有它我的 Hello, World 程序编译得很好.只有我定义的类在我身上失败了.

I know Thing does nothing, but my Hello, World program compiles just fine without it. It's only my defined classes that are failing on me.

它拒绝编译.我得到 No enclosure instance of Hello is access." 在创建新事物的行.我猜是:

And it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either:

  1. 我有系统级问题(在 DrJava 或我的 Java 安装中)或
  2. 我对如何在 java 中构建工作程序有一些基本的误解.

有什么想法吗?

推荐答案

static class Thing 将使您的程序工作.

事实上,您将 Thing 作为一个内部类,它(根据定义)与 Hello 的特定实例相关联(即使它从不使用或引用它),这意味着在范围内没有特定 Hello 实例的情况下说 new Thing(); 是错误的.

As it is, you've got Thing as an inner class, which (by definition) is associated with a particular instance of Hello (even if it never uses or refers to it), which means it's an error to say new Thing(); without having a particular Hello instance in scope.

如果您将其声明为静态类,则它是一个嵌套"类,不需要特定的 Hello 实例.

If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello instance.

相关文章