Inner Class Syntax

Contact Us or call 1-877-932-8228
Inner Class Syntax

Inner Class Syntax

[modifiers] class OuterClassName {
	[modifiers] class InnerClassName [extends BaseClassToInner] [SomeInterface[, MoreInterfaces, ...]] {
		fields and methods

The definition of the inner class is always available for the outer class to use. Note that:

  • No inner class objects are automatically instantiated with an outer class object.
  • Outer class code may instantiate any number of inner class objects - none, one, or many.

Code Sample:

public class MyOuter {
  private int x;
  MyOuter(int x, int y) {
    this.x = x;
    new MyInner(y).privateDisplay();
  public class MyInner {
    private int y;
    MyInner(int y) {
      this.y = y;
    private void privateDisplay() {
      System.out.println("privateDisplay x = " + x + " and y = " + y);
    public void publicDisplay() {
      System.out.println("publicDisplay x =  " + x + " and y = " + y);

This is a simple example of an inner class

  • MyOuter has one property, x; the inner class MyInner has one property, y.
  • The MyOuter constructor accepts two parameters; the first is used to populate x.
  • It creates one MyInner object, whose y property is populated with the second parameter.
  • Note that the inner class has free access to the private outer class x element.
  • The outer class has free access to the private inner class privateDisplay() method.

The connection between the two classes is handled automatically.

The following diagram maps out the memory used by the example.

Outer Class/Inner Class Memory Map