Java: Static vs inner class

This question already has an answer here:

  • Java inner class and static nested class 23 answers

  • 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 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.


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

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

  • The instance of non static inner class is created with the reference of object of outer class, in which it has defined, this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not 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(); 
        }
    }
    
    链接地址: http://www.djcxy.com/p/16376.html

    上一篇: 当我调用Thread对象的run()时,为什么我的Java程序会泄漏内存?

    下一篇: Java:静态与内部类