Java - 无法访问 Foo 类型的封闭实例 [英] Java - No enclosing instance of type Foo is accessible
问题描述
我有以下代码:
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.
它拒绝编译.我在创建新事物的行中得到 没有可访问的 Hello 类型的封闭实例."
.我猜:
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:
- 我有系统级问题(在 DrJava 或我的 Java 安装中)或
- 我对如何用 Java 构建工作程序有一些基本的误解.
有什么想法吗?
推荐答案
static class Thing
将使您的程序正常工作.
static class Thing
will make your program work.
实际上,您将 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.
这篇关于Java - 无法访问 Foo 类型的封闭实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!