Java Reference
In-Depth Information
Outer - printValue()...
Outer: Value = 1116
Inner - printValue()...
Inner: Value = 1720
Outer: Value = 1116
Setting Outer's value to 828
Outer - printValue()...
Outer: Value = 828
Inner - printValue()...
Inner: Value = 1720
Outer: Value = 828
Java restricts programmers from naming the inner class the same as its enclosing class. this is needed for
the inner classes to access the hidden members of their enclosing classes using the enclosing class name with the
keyword this .
Note
Restrictions on Accessing Local Variables
A local inner class is declared inside a block—typically inside a method of a class. A local inner class can access the
instance variables of its enclosing class as well as the local variables, which are in scope. The instance of an inner
class exists within an instance of its enclosing class. Therefore, accessing the instance variables of the enclosing
class inside a local inner class is not a problem because they exist throughout the life cycle of the instance of the
local inner class. However, the local variables in a method exist only during the execution of that method. All local
variables become inaccessible when method execution is over. Java makes a copy of the local variables that are used
inside a local inner class and stores that copy along with the inner class object. However, to guarantee that the values
of the local variables can be reproduced when accessed inside the local inner class code after the method call is over,
Java puts a restriction that the local variables must be effectively final . An effectively final variable is a variable whose
value does not change after it is initialized. One way to have an effectively final variable is to declare the variable
final . Another way is not to change its value after it is initialized. Therefore, a local variable or an argument to a
method must be effectively final if it is used inside a local inner class. This restriction also applies to an anonymous
inner class declared inside a method.
prior to Java 8, a local variable must be declared final if it is accessed inside a local inner class or an
anonymous class. Java 8 changed this rule: the local variable need not be declared final , but it should be
effectively final.
Tip
 
 
Search WWH ::




Custom Search