Java Reference
In-Depth Information
Notice the data type of the Inner reference is Outer.Inner . You only use this syntax in
situations where you are instantiating an inner class from somewhere else other than inside
its outer class, something not commonly done. Typically you instantiate inner objects from
within the enclosing class, using the this reference with the new operator:
Inner x = this.new Inner();
The Inner object that x refers to is associated with the Outer object that the this
reference refers to. The this reference is implied and can be omitted, but your code might
be clearer if you explicitly denote it.
Study the following Outer class and see if you can determine the output of its main
method:
1. public class Outer {
2. private String greeting;
3.
4. protected class Inner {
5. public int repeat = 3;
6. public void go() {
7. for(int i = 1; i <= repeat; i++) {
8. System.out.println(greeting);
9. }
10. }
11. }
12.
13. public void displayGreeting() {
14. Inner x = this.new Inner();
15. x.repeat = 2;
16. x.go();
17. }
18.
19. public static void main(String [] args) {
20. Outer y = new Outer();
21. y.greeting = “Hello, Outer”;
22. y.displayGreeting();
23. }
24.}
Running main causes the following sequence of events to occur:
1. An Outer object is instantiated within main and its displayGreeting method is
invoked from line 22.
2. One line 14, an Inner object is instantiated that is associated with the Outer object
from line 20.
Search WWH ::




Custom Search