Wednesday, January 19, 2011

Java Inner Class

There’s another twist. When you create an inner class, an object of that inner class has a link to the enclosing object that made it, and so it can access the members of that enclosing object—without any special qualifications. In addition, inner classes have access rights to all the elements in the enclosing class.At first, the creation of SequenceSelector looks like just another inner class. But examine it closely. Note that each of the methods—end( ), current( ), and next( )—refers to items, which is a reference that isn’t part of SequenceSelector, but is instead a private field in the enclosing class. However, the inner class can access methods and fields from the enclosing class as if it owned them.
01 interface Selector {
02 boolean end();
03
04 Object current();
05
06 void next();
07 }
08
09 public class Sequence {
10 private Object[] items;
11 private int next = 0;
12
13 public Sequence(int size) {
14 items = new Object[size];
15 }
16
17 public void add(Object x) {
18 if (next < items.length)
19 items[next++] = x;
20 }
21
22 private class SequenceSelector implements Selector {
23 private int i = 0;
24
25 public boolean end() {
26 return i == items.length;
27 }
28
29 public Object current() {
30 return items[i];
31 }
32
33 public void next() {
34 if (i < items.length)
35 i++;
36 }
37 }
38
39 public Selector selector() {
40 return new SequenceSelector();
41 }
42
43 public static void main(String[] args) {
44 Sequence sequence = new Sequence(10);
45 for (int i = 0; i < 10; i++)
46 sequence.add(Integer.toString(i));
47 Selector selector = sequence.selector();
48 while (!selector.end()) {
49 System.out.print(selector.current() + " ");
50 selector.next();
51 }
52 }
53 }
end