Please could you tell me if these two lines mean the same thing? Outer.Inner i = new Outer.Inner();// A Outer.Inner i = new Outer().new Inner(); // B If they are could you please tell me which is most appropriate version? Thanks 'Wale
First of all, remember: a)An instance of an inner class needs an instance of the containning class for being created. b)A non-inner (static) nested class doesn't need it. c)Within an instance method "this" points to the object over which the invocation was made. Within a constructor this points to the object being constructed. Now Outer.Inner i = new Outer.Inner();// A
If Inner was an inner class how would the Inner instance obtain such reference? The only way is if this invocation took place whitin an instance method of the containing class (or its subclasses)or whithing a constructor of the containing class (or its subclasses). Why? Because you are invoking new Outer.Inner() over "this" and only in those contexts "this" is an instance of a class container of Inner. If Inner was a static nested class A could be placed in any static method of the containning class (or its subclasses)or other class not being the containning one. But "new Inner()" could be placed only within a static method of the containning class or its subclasses. While Outer.Inner i = new Outer().new Inner(); // B If Inner was an inner class this expression could occur anywhere because you are providing to the instance of Inner the instance of the containning class that needs. But "new Inner()" would compile only if takes place in an instance method or constructor of the containning class (or its subclasses). The reason is because only in these contexts the hidden argument "this" points to an instance of the containning class (or its subclasses). If Inner was static nested, well, you can invoke a static method using an instance of the class isn't it? This is the same.
hope helps
Post by:autobot
There's a way to do it better - find it. -Edison. A better tiny ad:
a bit of art, as a gift, the permaculture playing cards