J2EEOnline J2EE






Java Certification  «Prev  Next»
Lesson 9Local Inner classes
Objective Using this with non-static inner classes

Cover local inner classes and the use of this with inner classes.

The keyword this refers to the current object instance. When using non-static inner classes, there is a this associated with the inner class and with its enclosing class. When this is used within the scope of the inner class, this refers to the instance of the inner class. When this is used outside the scope of the inner class, but within the scope of the outer class, this refers to the outer class. However, this can also be used to access the instance of the enclosing scope (outer class).
The notation Outer.this can be used within Inner to reference the this instance of Outer. The InnerThis program provides an example of using this within inner classes.
Scope:The extent of the context of a definition.

Creating instances of non-static inner classes

When an instance of a non-static inner class is created, it is created with respect to its enclosing instance. This enclosing instance must exist before the instance of the inner class can be created. When this refers to the enclosing instance, the constructor of the inner class may be invoked directly (i.e., new Inner()). The notation new Outer.Inner() may also be used in cases where it is not clear that an instance of the inner class is being constructed.

Local inner classes

Local inner classes are inner classes that are declared local to a block of code (e.g., local to a method). Local inner classes are not tied to an enclosing scope. Instead, they are treated as local variables. As such, they may not be declared as private, public, protected, or static. Local inner classes may only access the local variables or method parameters of the code block in which they are defined. Furthermore, these variables or parameters must be declared as final and assigned a value before being used.
The LocalInner program illustrates the use of local inner classes.
Local inner class: An inner class that is declared local to a block of code.