Forums Register Login

Inner Class

+Pie Number of slices to send: Send
Hi all,
How we create new object from non-static inner class and static inner class (nested class) ?
thanks
daniel
+Pie Number of slices to send: Send
Outer. Inner i = new Outer.Inner();
+Pie Number of slices to send: Send
Non-static inner class: you need an instance of the outer class:

Static inner classes (top level nested classes): you don't need an instance of the outer class:

HIH
Val
+Pie Number of slices to send: Send
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

------------------
+Pie Number of slices to send: Send
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

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
https://gardener-gift.com


reply
reply
This thread has been viewed 778 times.
Similar Threads
no static method in inner class - why ?
Question about static class
doubt on Inner class
is inner class can be static . what is the purpose of inner class ??
Top-level classes
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 04:54:59.