Java Reference
In-Depth Information
Let's make things a little complex by adding an instance variable named value to the inner class. Call the classes
Outer2 and Inner2 , as shown in Listing 2-15. Note that the instance variables for both Outer2 and Inner2 classes have
the same name as value .
Listing 2-15. A Member Inner Class Having the Same Instance Variable Name as Its Enclosing Class
// Outer2.java
package com.jdojo.innerclasses;
public class Outer2 {
// Instance variable for Outer2 class
private int value = 1116;
// Inner2 class starts here
public class Inner2 {
// Instance variable for Inner2 class
private int value = 1720;
public void printValue() {
System.out.println("Inner2: Value = " + value);
}
} // Inner2 class ends here
// Instance method for Outer class
public void printValue() {
System.out.println("Outer2: Value = " + value);
}
// Another instance method for Outer2 class
public void setValue(int newValue) {
this.value = newValue;
}
}
If you run the Outer2Test class shown in Listing 2-16, the output is different from the output when you ran the
OuterTest class in Listing 2-14.
Listing 2-16. Testing an Inner Class That Accesses the Instance Members of Its Enclosing Class
// Outer2Test.java
package com.jdojo.innerclasses;
public class Outer2Test {
public static void main(String[] args) {
Outer2 out = new Outer2();
Outer2.Inner2 in = out.new Inner2();
// Print the value
out.printValue();
in.printValue();
 
Search WWH ::




Custom Search