ChatGPT解决这个技术问题 Extra ChatGPT

Java: Static vs inner class [duplicate]

This question already has answers here: Java inner class and static nested class (28 answers) Closed 9 years ago.

What is the difference between static and non-static nested class?

Java doc Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.

R
Robert Harvey

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.


good answer. accessing static members from instances is so illogical. it should only be possible to access static members via SomeClass.StaticMember or, inside SomeClass, via StaticMember (without this.) then we wouldn’t get these questions at all.
@Brandon: When you say "static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested." ... It means without creating an object of the enclosing class right? Since as i see it, nested static class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. So, should be possible to access non-static members via an object.
H
Hearen

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.


I just was reading it . Item 22: Favor static member classes over nonstatic
Also Bloch notes that the reference to the enclosing instance in an unnecessary non static inner class could prevent garbage collect if retained.
When is one preferred over the other?
According to the Java Language Specification, there is no such thing as a static inner class. Bloch's book may be nice, but the JLS is the only normative reference here.
Reading the quote in this answer, I don't see it contradicting the JLS. On the contrary, it appears to confirm it.
A
Arun Kumar Mohan

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(); 
    }
}

As one of them doesn't exist, the difference is infinite.
Examples really help =)
Solved Both doubts(Static/nonStatic) in one Example, very neat!
n
nhahtdh

Static inner class cannot access non-static members of enclosing class. It can directly access static members (instance field and methods) of enclosing class same like the procedural style of getting value without creating object. Static inner class can declare both static and non-static members. The static methods have access to static members of main class. However, it cannot access non-static inner class members. To access members of non-static inner class, it has to create object of non-static inner class. Non-static inner class cannot declare static field and static methods. It has to be declared in either static or top level types. You will get this error on doing so saying "static fields only be declared in static or top level types". Non-static inner class can access both static and non-static members of enclosing class in procedural style of getting value, but it cannot access members of static inner class. The enclosing class cannot access members of inner classes until it creates an object of inner classes. IF main class in accessing members of non-static class it can create object of non-static inner class. If main class in accessing members of static inner class it has two cases: Case 1: For static members, it can use class name of static inner class Case 2: For non-static members, it can create instance of static inner class.


Would you please fix the grammar in places like "IF main class in accessing members of non-static class" or "If main class in accessing members of static inner class". I have no idea what you are trying to say there.
H
Hearen

Discussing nested classes...

The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.

When you have a nested class declaration that is not static, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.

But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.


V
Vijay Kumar

static inner class: can declare static & non static members but can only access static members of its parents class.

non static inner class: can declare only non static members but can access static and non static member of its parent class.


There are no "static inner class", and (non static) inner class can declare some kind of static members. JLS 8.1.3: An inner class is a nested class that is not explicitly or implicitly declared static. [...] Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).
k
kathir

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?".

as u said here inner class cannot be static... i found the below code which is being given static....reason? or which is correct....

Yes, there is nothing in the semantics of a static nested type that would stop you from doing that. This snippet runs fine.

    public class MultipleInner {
        static class Inner {
        }   
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Inner();
        }
    }
}

this is a code posted in this website...

for the question---> Can a Static Nested Class be Instantiated Multiple Times?

answer was--->

Now, of course the nested type can do its own instance control (e.g. private constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is a static enum, of course you can't instantiate it at all.

But in general, yes, a static nested type can be instantiated multiple times.

Note that technically, a static nested type is not an "inner" type.


E
Emil

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.