Local variable age defined in an enclosing scope must be final or effectively final

标题:Local variable age defined in an enclosing scope must be final or effectively final

原因是:被匿名内部类访问的局部变量,相当于被final修饰了,故只能赋一次值;

如下代码,注释了 age=6;故编译器不会报错,若不注释age=6;则报Local variable age defined in an enclosing scope must be final or effectively final

interface A{
     
	void test();
}
public class DemoInner03{
     
	public static void main(String[] args) {
     
		int age=8;
//		age=6;

		A a=new A() {
     
			public void test() {
     
				System.out.println("哈哈哈,真轻松!!!");
				System.out.println(age);
			}
		};
		a.test();
	}
}

你可能感兴趣的:(#,java基础)