Java: Static vs inner class [duplicate]
Asked Answered
P

8

384

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

Proglottis answered 30/8, 2009 at 7:12 Comment(1)
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.False
G
584

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.

Glengarry answered 30/8, 2009 at 7:22 Comment(2)
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.Impermissible
@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.Aruwimi
C
143

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.

Cheju answered 30/8, 2009 at 7:24 Comment(6)
I just was reading it . Item 22: Favor static member classes over nonstaticVogler
Also Bloch notes that the reference to the enclosing instance in an unnecessary non static inner class could prevent garbage collect if retained.Trochophore
When is one preferred over the other?Wisent
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.Rapine
Reading the quote in this answer, I don't see it contradicting the JLS. On the contrary, it appears to confirm it.Norenenorfleet
@Norenenorfleet Of course. The point is that you should prefer primary sources over others.Rapine
H
76

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

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

  2. 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(); 
    }
}
Harelip answered 7/12, 2012 at 18:3 Comment(3)
As one of them doesn't exist, the difference is infinite.Rapine
Examples really help =)Nebulous
Solved Both doubts(Static/nonStatic) in one Example, very neat!Vatic
E
18
  1. 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.

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

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

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

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

  6. 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.
Exoskeleton answered 20/2, 2013 at 9:44 Comment(1)
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.Tumid
F
11

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.

Formosa answered 30/8, 2009 at 7:27 Comment(0)
P
3

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.

Prenotion answered 1/6, 2011 at 13:58 Comment(1)
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).Broadax
L
3

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.

Lichter answered 29/12, 2012 at 6:23 Comment(0)
A
2

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.

Agronomy answered 23/11, 2011 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.