bsp; public void intanceMethod() { //define a local class in its out class' instance method class Inner3 { } //local class is visible only in its containning code block //Outer.Inner2 inner2; } private static void staticMethod() { //define a local static member class in its out class' static method class Inner4 { public Inner4() { staticField = 2; } } //can not define a interface as a local class /*interface I { }*/ } }
3.1 局部类特性 如示例代码所示,局部类能且只能访问其所属代码段中的声明为final的局部 变量。为什么只能访问声明为final的局部变量呢?我们知道,局部变量在其所属的代码段(譬如某个函数)执行完毕后就会被回收,而一个局部类的实例却可以在其类定义所属代码段执行完毕后依然存在,如果它可操控非final的局部变量,用户就可以通过该实例修改已不存在的局部变量,无意义。 3.2 局部类约束
如示例代码所示,内部类只在定义它的代码段中可见,不能在它所属代码段之外的代码中使用;因此也就没有public/private/default权限修饰符(无意义)
不能以局部类形式定义一个接口。局部类只在其所属代码段中可见,定义这样的接口无意义
局部类类名不能与其外部类类名重复 3.3 什么时候使用局部类 局部类大部分以匿名类的形式使用。 4 Anonymous class(匿名类) 没有类名的局部类就是匿名类。用一条语句完成匿名类的定义与实例创建。例 如如下代码: public class Outer { public void instanceMethod() { //define a nonymous class which implements Action interface and creat an instance of it Action action = new Action() { public void doAction() { System.out.println("a simple anonymous class demo"); }}; &nbs上一页 [1] [2] [3] [4] [5] [6] [7] 下一页
|