Referencing the Outer Class Instance from the Inner Class Code

Contact Us or call 1-877-932-8228
Referencing the Outer Class Instance from the Inner Class Code

Referencing the Outer Class Instance from the Inner Class Code

If inner class code needs a reference to the outer class instance that it is attached to, use the name of the outer class, a dot, and this. Remember that if there is no name conflict, there is no need for any special syntax.

For code in MyInner to obtain a reference to its MyOuter:

MyOuter.this

static Inner Classes

An inner class may be marked as static.

A static inner class my be instantiated without an instance of the outer class. Note that:

  • static members of the outer class are visible to the inner class, no matter what their access level.
  • Non-static members of the outer class are not available, since there is not instance of the outer class to retrieve them from.

To create a static inner class object from outside the enclosing class, you must still reference the outer class name

new OuterClassName.InnerClassName(arguments)

An inner class may not have static members unless the inner class is itself marked as static.

Code Sample:

Java-InnerClasses/Demos/StaticInnerTest.java
class StaticOuter {
  public StaticInner createInner() {
   return new StaticInner();
  }

  static class StaticInner {
    public void display() {
      System.out.println("StaticOuter.Inner display method");
    } 
  }
}

class StaticInnerTest  {
  public static void main(String[] args) {
    
    new StaticOuter.StaticInner().display();
    
    StaticOuter so = new StaticOuter();
    
    //so.new StaticInner().display();
    
    so.createInner().display();

 
  }
}

We have a class StaticOuter that declares a static inner class StaticInner. StaticOuter has a method that will create instances of StaticInner. But, StaticInner also has a public constructor. Note that:

  • We can directly instantiate a StaticOuter.StaticInner object without an outer class instance.
  • Code for a StaticOuter can create a StaticInner, but the inner class object has no attachment to the outer class object that created it.
  • Note the commented out line; you cannot create a static inner class instance attached to an instance of its enclosing class.
Next