Instantiating an Inner Class Instance from within the Enclosing Class

Contact Us or call 1-877-932-8228
Instantiating an Inner Class Instance from within the Enclosing Class

Instantiating an Inner Class Instance from within the Enclosing Class

An inner class instance may be directly instantiated from code in the enclosing class, without any special syntax:

[modifiers] class OuterClassName {
	code
	[modifiers] class InnerClassName {
		code
	}
	public void someMethod() {
		InnerClassName variable = new InnerClassName();
	}
}

Such an instance is automatically associated with the enclosing class instance that instantiated it.

Code Sample:

Java-InnerClasses/Demos/Inner1.java
public class Inner1 {
  public static void main(String[] args) {
    new MyOuter(1, 2);
  }
}

This code simply creates an instance of the outer class, MyOuter.

The MyOuter constructor creates an instance of MyInner as mentioned earlier.

Next