Java Reference
In-Depth Information
Local Inner Classes
A local inner class is a nested class defi ned within a method. Like local variables, a local
inner class declaration does not exist until the method is invoked, and it goes out of scope
when the method returns. That means if you defi ne an inner class locally, you can only
create instances from within the method. Local inner classes have the following properties:
Local inner classes do not have an access specifier.
Local inner classes cannot be declared static , nor can they declare static fields or
methods.
Local inner classes have access to all the fields and methods of its enclosing class.
A local inner class does not have access to the local variables of method unless those
variables are final .
It might seem odd that a local inner class cannot access a local variable, but recall that
the compiler generates a top-level class from your inner class declaration. It is not possible
for a top-level class to have access to a local variable from a method in another class.
However, if the local variable is final , then a copy of the local variable can be stored in the
generated top-level class, which is exactly what the compiler does behind the scenes.
The following class demonstrates a local inner class. Examine the code and see if you
can determine what its output is:
1. public class LocalInner {
2.
3. public double radius;
4.
5. public void doSomething() {
6. final double pi = 3.1415;
7.
8. class Circle {
9. public double area() {
10. return pi * radius * radius;
11. }
12. }
13.
14. Circle c = new Circle();
15. System.out.println(c.area());
16. }
17.
18. public static void main(String [] args) {
19. LocalInner x = new LocalInner();
Search WWH ::




Custom Search