views:

2866

answers:

4

What is the difference between static and non static inner class?

A: 

I would imagine a static inner class would produce a shared instance (of that class) that all common classes can use. A non static inner class would then be a normal inner class. I could be wrong, the term static class seems troubling...

Ori Cohen
+9  A: 

An inner class cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?".

A non-static nested class (or 'inner class') has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

Brandon E Taylor
thanks for answer with description
Abhishek Sanghvi
+4  A: 

Let's look in the source of wisdom for such questions: Joshua Bloch's "Effective Java":

Technically, there is no such thing as a static inner class. According to "Effective Java", the correct terminology is a "static nested class". A non-static nested class is indeed an inner class, along with anonymous classes and local classes.

And now to quote: "Each instance of a nonstatic [nested] class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance."

A static nested class does not have access to the enclosing instance. It uses less space too.

Steve McLeod
A: 

Actually, all it means is that a nested class declaration that is also static can be instantiated outside of the enclosing class.

DigitalRoss