Instantiating Java inner-class objects, from a different class.
Tuesday, January 9th, 2007It occurred to me one day, that if you’re inner class isn’t static, it needs to have a copy of the “this” reference of the outer class. Most of the time, inner classes are only instantiated from within the containing outer class, so it was apparent where the “outer.this” reference came from.
I started thinking of how one might instantiate the inner-class object from a completely separate class. I spent a little time experimenting, why bother reading the JLS, and found the right syntax.
I first tried “new outerObject.InnerClass()”, but that was a syntax error. My second try was the right one. “outerObject.new InnerClass()”. While it looks a little awkward (and I would never do it in production code), it is useful to know how it works. I wrote up an example program to demonstrate how it happens.
(more…)
