Java Reference
In-Depth Information
The program in Listing 2-21 demonstrates the rules for accessing local variables inside a local inner class. The
main()
method declares two local variables called
x
and
y
. Both variables are effectively final. The variable
x
is never
changed after it is initialized and the variable
y
cannot be changed because it is declared as
final
.
Listing 2-21.
Accessing Local Variables Inside localclasses
// AccessingLocalVariables.javapackage com.jdojo.innerclasses;
public class AccessingLocalVariables {
public static void main(String... args) {
int x = 100;
final int y = 200;
class LocalInner {
void print() {
// Accessing the local varibale x is fine as
// it is effectively final.
System.out.println("x = " + x);
// The local variable y is effectively final as
// it has been declared final.
System.out.println("y = " + y);
}
}
/* Uncommenting the following statement will make the variable x no longer
an effectively final variable and the LocalIneer class wil not compile.
*/
// x = 100;
LocalInner li = new LocalInner();
li.print();
}
}
x = 100
y = 200
Inner Class and Inheritance
An inner class can inherit from another inner class, a top-level class, or its enclosing class. For example, in the
following snippet of code, inner class
C
inherits from inner class
B
; inner class
D
inherits from its enclosing top-level
class
A
, and inner class
F
inherits from inner class
A.B
:
public class A {
public class B {
}
public class C extends B {
}