我最近遇到了一种罕见但完全合法的语法:Local Classes。
我想知道为什么我不能访问该方法之外的本地类?与内部类有什么不同,内部类可以在外部类中访问,或者使用封闭对象(outer.new Inner()
)?
示例:这完全有效,
//this is valid
public class Outer {
int outer_x = 100;
public void test() {
Inner inner = new Inner();
inner.display();
}
public class Inner {
public void display() {
System.out.println("Outer x is: " + outer_x);
}
}
}
这也是有效的
//this is valid as well
public class Outer {
int outer_x = 100;
public void test() {
Inner inner = new Inner();
inner.display();
}
public class Inner {
public void display() {
System.out.println("Outer x is: " + outer_x);
}
}
public void test2() {
Inner inner2 = new Inner();
inner2.display();
}
}
但这不会编译:
public class Outer {
int outer_x = 100;
public void test() {
class Inner {
public void display() {
System.out.println("Outer x is: " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
public void test2() {
Inner inner2 = new Inner(); // error here
inner2.display();
}
}
为什么会这样?
答案 0 :(得分:0)
因为每次调用test()
都会创建一个完整的新版本的类。因此,它可以访问(最终或有效最终)局部变量!
这里有一个简介。
public class Outer {
public void test(int i) {
class Inner {
private int x = i; // i may be different on each call of test
public void display() {
System.out.println("Inner x is: " + x);
}
}
Inner inner = new Inner();
inner.display();
}
public void test2() {
test(1); // prints 1
test(2); // prints 2
//now imagine this is valid
Inner inner2 = new Inner();
inner2.display();// what's the value of x??
}
}