20080320

Inner classes

One great thing with pair programming is that you learn everyday from your pair and sometimes very funny things.

Today it was a new way on how to use an inner java class:

class Foo {
  ...
  class InnerFoo {...}
  ...
}

An instance of InnerFoo can only exist within an instance of Foo and has direct access to the methods and fields of its enclosing instance.
And to instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object:

Foo foo = new Foo();
Foo.InnerFoo innerFoo = foo.new InnerFoo();

Ok nothing huge but I swear I never used that syntax before, well at least not explicitly.
In fact most java developers have used it in someway and without knowing it like me:

class Foo {
  Foo() {
    this.new InnerFoo(); // or just new InnerFoo()
  }

  class InnerFoo {...}


}

No comments: