Inner classes

Non-static inner class:
– holds the reference to the enclosing outer class: Outer.this
– has access to both static and non-static fields/methods from the enclosing class:
Outer.staticMethod() or Outer.this.nonStaticMethod()
– cannot declare static fields/methods/inner classes (nested classes)
– can declare non-static fields/methods/inner classes
– is created in two steps by creating an instance of the outer class and then invoking the .new and the inner class constructor on that instance reference:
Outer o = new Outer();
Outer.NonStaticInner nsi = o.new NonStaticInner();

Static inner class (nested class):
– doesn’t hold the reference to the enclosing class
– has access only to static fields/methods from the enclosing class: Outer.staticMethod() or Outer.staticField
– cannot access enclosing class instance methods/fields since it cannot use Outer.this
– can declare both static and non-static fields/methods/inner classes
– is created directly by new and the inner class constructor
Outer.StaticInner si = new Outer.StaticInner();

Inheriting from an inner class
Due to the fact that inner class constructor must attach to a reference of the enclosing class object, a class inheriting from an inner class must have a constructor with a reference to the outer class as an argument and this constructor must explicitly call super() on that reference in order to compile:

public class ExtendingInner extends OuterWithInner.Inner {
   ExtendingInner(OuterWithInner owi) { owi.super(); }
   public static void main(String[] args) {
      new ExtendingInner(new OuterWithInner());
   }
}

Usage

Static nested class: to declare a component that the enclosing type is composed of, this component does not use any other member fields/methods of the enclosing class, e.g. static class Entry<K,V>{K key; V value; + getters/setters} in the java.util.Map impls.

Non-static inner class: to adapt the view of enclosing type instance into view of unrelated class, e.g. view the enclosing class Entry[] array and present it as an interable collection, ie. private class MyIterator implements Iterator to iterate over entries and a getter method returning new instance of that iterator. The inner MyIterator class has to be non-static to access enclosing type entries.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s