Java Reference
In-Depth Information
// Inner class starts here
public class Inner {
public void printValue() {
System.out.println("Inner: Value = " + value);
}
} // Inner class ends here
// Instance method for the Outer class
public void printValue() {
System.out.println("Outer: Value = " + value);
}
// Another instance method for the Outer class
public void setValue(int newValue) {
this.value = newValue;
}
}
The Outer class has a private instance variable called value , which is initialized to 1116. It also defines two
instance methods: printValue() and setValue() . The Inner class defines an instance method called printValue() ,
which prints the value of the value instance variable of its enclosing class Outer .
Listing 2-14 creates an instance of the Inner class and invokes its printValue() method. The output shows that
the inner class instance can access the instance variable value of its enclosing instance out .
Listing 2-14. Testing an Inner Class That Accesses the Instance Members of its Enclosing Class
// OuterTest.java
package com.jdojo.innerclasses;
public class OuterTest {
public static void main(String[] args) {
Outer out = new Outer();
Outer.Inner in = out.new Inner();
// Print the value
out.printValue();
in.printValue();
// Set a new value
out.setValue(828);
// Print the value
out.printValue();
in.printValue();
}
}
Outer: Value = 1116
Inner: Value = 1116
Outer: Value = 828
Inner: Value = 828
 
Search WWH ::




Custom Search