Studyon Minte9.com
Fundamentals (Docs)

Study

Nested Classes



The Java programming language allows you to define a class within another class. 
	class OuterClass {
	    ...
	    class NestedClass {
		...
	    }
	}

Logical grouping of classes
If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.

Increased encapsulation
Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be 
declared private. 
By hiding class B within class A, A's members can be declared private and B can access them. 
In addition, B itself can be hidden from the outside world.

More readable, maintainable code
Nesting small classes within top-level classes places the code closer to where it is used.

Instantiate
To instantiate an inner class, you must first instantiate the outer class. 
Then, create the inner object within the outer object with this syntax:
	class OuterClass {
	    ...
	    class InnerClass {
		...
	    }
	}
        outerObject = new OuterClass();
	OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Example

	public class ClassInnerDemo {
	    
	    private final static int SIZE = 15;
	    private int[] arrayOfInts = new int[SIZE];
	    
	    public static void main (String[] args) {
		ClassInnerDemo id = new ClassInnerDemo();
		id.printEven();
	    }
	    
	    public ClassInnerDemo() {
		for (int i=0; i<SIZE; i++) {
		    arrayOfInts[i] = i;
		}
	    }
	    
	    public void printEven() {
		InnerEventIterator iterator = new InnerEventIterator();
		while (iterator.hasNext()) {
		    System.out.print(iterator.getNext() + " ");
		}
	    }
	    
	    private class InnerEventIterator {
		
		private int next = 0;
		
		public boolean hasNext() {
		    return (next <= SIZE - 1); // check if current element is the last in array
		}
		
		public int getNext() {
		    int currValue = arrayOfInts[next];
		    next += 2;
		    return currValue;
		}
	    }
	}

	// 0 2 4 6 8 10 12 14


http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html