| Author |
Difference between static inner class and inner class
|
ying lam
Ranch Hand
Joined: May 17, 2004
Posts: 85
|
|
Hi, Can someone please tell me what are the difference between static inner class and inner class? I know both can access the outer class private and protected attributes, but what are the difference between 'static' vs 'non-static'? And when I should use which one?
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
A non-static one is "connected" to an instance of the outer class; for example, this code works because each Inner instance is connected to an "Outer" instance: But if you make Inner static, then this doesn't compile. Inner could still access "i" in an Outer object, but there's not an implicit Outer object as there is in this example. In other words, you can create an instance of a static inner class without ever creating an instane of the outer class, but a non-static one requires such an instance.
|
[Jess in Action][AskingGoodQuestions]
|
 |
ying lam
Ranch Hand
Joined: May 17, 2004
Posts: 85
|
|
Thank you. You said, for the static inner class case:
Inner could still access "i" in an Outer object, but there's not an implicit Outer object as there is in this example
How canit access 'i' in an outer object if the above code you shown won't compile once you make the class 'static inner'.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
Originally posted by ying lam: Thank you. You said, for the static inner class case: How canit access 'i' in an outer object if the above code you shown won't compile once you make the class 'static inner'.
A static version of Inner could still include code like Outer o = new Outer(); o.i = 3; It can still access i, it just doesn't have its own implicit copy of i.
|
 |
 |
|
|
subject: Difference between static inner class and inner class
|
|
|