我是 java 的新手,正在尝试一些访问方法,但遇到了一些我不明白的事情。下面的代码工作正常,打印 9 并且没有给出任何编译错误。 我认为这段代码应该给出一个编译错误并且数字应该无法从测试方法访问,因为 new Human() 是一个完全不同的类的实例。任何人都可以向我解释这里发生了什么吗?
public class Test{
public static void main(String[] args) {
int number = 9;
test("holla",new Human(){
@Override
void test() {
// TODO Auto-generated method stub
System.out.println(number); // I think this line should not compile
}
});
}
private static void test(String a ,Human h){
h.test();
}
}
人类类
public abstract class Human {
abstract void test();
}
最佳答案
java 8之前你是对的.
In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter.
局部变量应该是 final
以便在匿名类中访问。
从 Java 8 开始,effectively final 变量也允许在内部访问。
However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
尝试
int number = 9;
number=10;
现在 number
根本不是 effectively final 并且您会收到一个编译器错误,提示 “在封闭范围内定义的局部变量号必须是 final 或 effectively final “。
关于java - 通过java中的内联创建对象访问私有(private)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45817630/