Java: Static vs inner class [duplicate] Java: Static vs inner class [duplicate] java java

Java: Static vs inner class [duplicate]


An inner class, by definition, 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 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.


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 non-static 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.


There are two differences between static inner and non static inner classes.

  1. In case of declaring member fields and methods, non staticinner class cannot have static fields and methods.But, in case of static inner class, can have static and non static fieldsand method.

  2. The instance of non static inner class is created with the referenceof object of outer class, in which it has defined, this means it hasenclosing instance. But the instance of static inner class iscreated without the reference of Outer class, which means it doesnot have enclosing instance.

See this example

class A{    class B    {        // static int x; not allowed here    }    static class C    {        static int x; // allowed here    }}class Test{    public static void main(String… str)    {        A a = new A();        // Non-Static Inner Class        // Requires enclosing instance        A.B obj1 = a.new B();         // Static Inner Class        // No need for reference of object to the outer class        A.C obj2 = new A.C();     }}