File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Difference between static inner class and inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Difference between static inner class and inner class" Watch "Difference between static inner class and inner class" New topic
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
    
  15

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
    
  15

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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Difference between static inner class and inner class
 
Similar Threads
Inner class
Nested vs Inner
Inner class
nested vs inner classes
nested class and inner class