Java Reference
In-Depth Information
If the instance variable name is hidden, you must qualify its name with the keyword this or the class name as
well as the keyword this . The code inside an inner class always executes in the context of more than one current
instance. The number of current instances depends on the level of nesting of the inner class. Consider the following
class declaration:
public class TopLevelOuter {
private int v1 = 100;
// Here, only v1 is in scope
public class InnerLevelOne {
private int v2 = 200;
// Here, only v1 and v2 are in scope
public class InnerLevelTwo {
private int v3 = 300;
// Here, only v1, v2, and v3 are in scope
public class InnerLevelThree {
private int v4 = 400;
// Here, all v1, v2, v3, and v4 are in scope
}
}
}
}
When the code for the InnerLevelThree class is executed, there are four current instances: one for the
InnerLevelThree class and one for each of its three enclosing classes. When the code for the InnerLevelTwo class is
executed, there are three current instances: one for the InnerLevelTwo class and one for each of its two enclosing classes.
When the code for the TopLevelOuter class is executed, there is only one current instance because it is a top-level class.
When the code for an inner class is executed, all instance members, instance variables, and methods of all current
instances are in scope unless hidden by local variable declarations.
The above example has comments indicating which instance variables are in the scope in an inner class. When
an instance member is hidden inside an inner class, you can always refer to the hidden member by using the keyword
this qualified with the class name. Listing 2-19 is the modified version of Listing 2-15. It illustrates the use of the
class name with the keyword this to refer to the instance member of the enclosing class of an inner class. Listing 2-20
contains the code to test the ModifiedOuter2 class.
Listing 2-19. Using the Keyword this Qualified with the Class Name
// ModifiedOuter2.java
package com.jdojo.innerclasses;
public class ModifiedOuter2 {
// Instance variable for ModifiedOuter2 class
private int value = 1116;
 
Search WWH ::




Custom Search