为什么我不能在声明方法之外访问本地 class?
Why can't I access local class outside declaring method?
我最近遇到了一种罕见但完全合法的语法:Local Classes.
我想知道为什么我不能在该方法之外访问本地 class?它与可以在外部 class 或封闭对象 (outer.new Inner()
) 中访问的内部 class 有何不同?
示例:这是完全有效的,
//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();
}
}
为什么会这样?
因为每次调用 test()
都会创建一个完整的新版本 class。因此它可以访问(最终或有效最终)局部变量!
这里是正在发生的事情的概要。
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??
}
}
我最近遇到了一种罕见但完全合法的语法:Local Classes.
我想知道为什么我不能在该方法之外访问本地 class?它与可以在外部 class 或封闭对象 (outer.new Inner()
) 中访问的内部 class 有何不同?
示例:这是完全有效的,
//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();
}
}
为什么会这样?
因为每次调用 test()
都会创建一个完整的新版本 class。因此它可以访问(最终或有效最终)局部变量!
这里是正在发生的事情的概要。
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??
}
}