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!");
}
}
我知道事情
什么都不做,但我的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的封闭实例。
在创建新Thing的行上。我猜是:
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
的特定实例相关联(即使它从未使用过)或者引用它),这意味着说 new Thing();
而没有特定的 Hello
实例是错误的在范围内。
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
instance。
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屋!