No enclosing instance of type Zero_one_Knapsack is accessible. Must qualify the allocation with an enclosing instance of type Zero_one_Knapsack (e.g. x.new A() where x is an instance of Zero_one_Knapsack).
时间: 2024-03-14 08:47:31 浏览: 15
这个错误通常发生在内部类访问外部类的成员变量或方法时,由于内部类是非静态的,所以需要使用外部类的实例来访问。如果在没有外部类实例的情况下创建了内部类的实例,就会出现这个错误。
解决这个问题的方法是,要么将内部类改成静态的,要么在创建内部类的实例时,使用外部类的实例来限定。
例如,假设有一个非静态的内部类 A,需要访问外部类 Zero_one_Knapsack 的成员变量 value,可以将代码修改为以下两种方式之一:
1. 将内部类 A 改成静态的:
```
public class Zero_one_Knapsack {
int value = 10;
static class A {
void method() {
Zero_one_Knapsack zok = new Zero_one_Knapsack();
System.out.println(zok.value);
}
}
public static void main(String[] args) {
Zero_one_Knapsack.A a = new Zero_one_Knapsack.A();
a.method();
}
}
```
2. 在创建内部类 A 的实例时,使用外部类 Zero_one_Knapsack 的实例来限定:
```
public class Zero_one_Knapsack {
int value = 10;
class A {
void method() {
System.out.println(Zero_one_Knapsack.this.value);
}
}
public static void main(String[] args) {
Zero_one_Knapsack zok = new Zero_one_Knapsack();
Zero_one_Knapsack.A a = zok.new A();
a.method();
}
}
```
这样就可以避免出现上述错误。