package test;/** * * 局部内部类能不能访问外围方法或者属性的值 ? * * 局部内部类可以访问属性 ,但是不能访问非final的局部变量 * */public class Test1 { private String attribute ; public void f(){ final String localAttribute = "" ; class InnerClass { public InnerClass(){ System.out.println("attribute " + attribute ); attribute = attribute + "" ; //Cannot refer to //the non-final local variable localAttribute //defined in an enclosing scope System.out.println("localAttribute " + localAttribute ); localAttribute = localAttribute + "" ; } } }}/** * 测试任意代码块中的内部类访问属性和局部变量 */class TestIfLocalClass { private String attribute ; public TestIfLocalClass(){ final String localAttribute = "" ; if(true){ class IfLocalClass { public IfLocalClass(){ System.out.println(attribute); attribute = attribute + "" ; System.out.println(localAttribute); localAttribute = localAttribute + "" ; } } } }}/** * 测试匿名内部类对外围属性和本地变量的访问 */interface TestAnonymousClass{ public void f() ;}class TestAClass{ private String attribute ; public TestAnonymousClass f(){ final String localAttribute = "" ; return new TestAnonymousClass(){ @Override public void f() { System.out.println(attribute); attribute = attribute + "" ; System.out.println(localAttribute); localAttribute = localAttribute + "" ; } } ; }}
通过上面的测试可得,局部内部类能够访问和修改外部类的属性但是不能访问非final修饰的局部变量,可以访问final修饰的局部变量但是不能修改其值。