What causes error quot;No enclosing instance of type Foo is accessiblequot; and how do I fix it?(是什么导致错误“无法访问 Foo 类型的封闭实例?我该如何解决?)
问题描述
我有以下代码:
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:
- 我有系统级问题(在 DrJava 或我的 Java 安装中)或
- 我对如何在 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.
这篇关于是什么导致错误“无法访问 Foo 类型的封闭实例"?我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是什么导致错误“无法访问 Foo 类型的封闭实例"?我该如何解决?
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01