Nested and Inner Classes

Nested Classes

The Java programming language allows you to define a class within another class. Such a class is called a nested class:

class OuterClass {
  ...
  class NestedClass {
    ...
  }
}

A nested class is a member of its enclosing class and, as such, has access to other members of the enclosing class, even if they are declared private. As a member of OuterClass, a nested class can be declared private, public, protected, or package private.

Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object’s methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
  ...
  class InnerClass {
    ...
  }
}

Example as :

public class NestedClass {
	private String outer = "Outer Class"; // NestedClass instance variable
	InnerClass innerClass = new InnerClass();

	void getOuterS() {
		System.out.println(outer);
	}
	void getInnerS() {
		System.out.println(innerClass.inner);
	}
	class InnerClass {
		private String inner = "Inner Class"; // InnerClass instance variable,
												// uninitialized
		void getInnerS() {
			System.out.println(inner);
		}

		void getOuterS() {
			System.out.println(NestedClass.this.outer);
		}
	}

	public static void main(String[] args) {
		NestedClass nestedClass = new NestedClass();
		NestedClass.InnerClass nestedInner = nestedClass.new InnerClass();
		/* can also be new NestedClass().new InnerClass (); */
		nestedClass.getOuterS();
		nestedClass.getInnerS();
		nestedInner.getInnerS();
		nestedInner.getOuterS();
	}
}