Accessing Members of an Enclosing Class
2016-04-23 12:28
323 查看
A local class has access to the members of its enclosing class. In the previous example, the PhoneNumber
constructor
accesses the member LocalClassExample.regularExpression
.
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 orparameter of the enclosing block, it captures that variable or parameter. For example, the
PhoneNumberconstructor can access the local variable
numberLengthbecause
it is declared final;
numberLengthis acaptured variable.
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. For example, suppose that the variable
numberLengthis
not declared final, and you add the highlighted assignment statement in the
PhoneNumberconstructor:
PhoneNumber(String phoneNumber) { numberLength = 7; String currentNumber = phoneNumber.replaceAll( regularExpression, ""); if (currentNumber.length() == numberLength) formattedPhoneNumber = currentNumber; else formattedPhoneNumber = null; }
Because of this assignment statement, the variable
numberLengthis not effectively final anymore. As a result, the Java compiler
generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class
PhoneNumbertries to access the
numberLengthvariable:
if (currentNumber.length() == numberLength)
Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters. For example, you can define the following method in the
PhoneNumberlocal
class:
public void printOriginalNumbers() { System.out.println("Original numbers are " + phoneNumber1 + " and " + phoneNumber2); }
The method
printOriginalNumbersaccesses the parameters
phoneNumber1and
phoneNumber2of
the method
validatePhoneNumber.
相关文章推荐
- c语言全局变量和局部变量问题及解决汇总
- 深入探讨C语言中局部变量与全局变量在内存中的存放位置
- sqlserver 局部变量的使用
- 全局变量与局部变量在内存中的区别详细解析
- 关于全局变量和局部变量的那些事
- javascript中局部变量和全局变量的区别详解
- javascript 用局部变量来代替全局变量第1/2页
- android中写一个内部类来选择文件夹中指定的图片类型实例说明
- c++静态局部变量和静态函数示例
- 基于java内部类作用的深入分析
- awk实现Left、join查询、去除重复值以及局部变量讲解例子
- 深入解析Java中的内部类
- phpinfo() 中 Local Value(局部变量)Master Value(主变量) 的区别
- Android中的全局变量与局部变量使用小结
- Android中的全局变量与局部变量使用小结
- 探讨:程序在内存中的分配(常量,局部变量,全局变量,程序代码)问题
- 对Java的面对对象编程中对象和引用以及内部类的理解
- java中的内部类详细总结
- 全面解读Java编程中的内部类
- Java嵌套类和内部类详解