What's the advantage of making an inner class as static with Java?
Asked Answered
H

6

37

I have an inner class in my Java class.

enter image description here

When I run find bugs, it recommends(warns) to make it as static.

enter image description here

What's the point of this warning? What's the advantage of making a inner class as static?

Haiti answered 22/4, 2013 at 12:42 Comment(3)
possible duplicate of Java inner class and static nested classFortress
The linked question is not a duplicate - it does not indicate advantages or disadvantages of making an inner class static.Struthious
possible duplicate of Static nested class in Java, why?Incitement
D
37

If the nested class does not access any of the variables of the enclosing class, it can be made static. The advantage of this is that you do not need an enclosing instance of the outer class to use the nested class.

Diaconicon answered 22/4, 2013 at 12:45 Comment(3)
+1 I just ran into this problem creating a Mana Potion in my Potion class but forgetting to declare it static made it impossible to declare new ManaPotion().Felon
@Felon - Inheritance is a strong indicator that ManaPotion should not be an inner class of Potion. A good positive example is Map using Map.Entry instances to hold its entries. Will Potion use Potion.ManaPotion? This applies even for static inner classes.Balinese
True, it was for the sake of testing which is pretty much the only time I use nested classes.Felon
D
17

An inner class, by default, has an implicit reference to an object of the outer class. If you instantiate an object of this from the code of the outer class, this is all done for you. If you do otherwise you need to provide the object yourself.

A static inner class does not have this.

That means it can be instantiated outside the scope of an outer class object. It also means that if you 'export' an instance of the inner class, it will not prevent the current object to be collected.

As a basic rule, if the inner class has no reason to access the outer one, you should make it static by default.

Dipietro answered 22/4, 2013 at 12:45 Comment(1)
I love the basic rule, that's you defined.Serf
R
9

A static inner class is a semantically simpler thing. It's just like a top-level class except you have more options for visibility (e.g. you can make it private).

An important reason to avoid non-static inner classes is that they are more complex. There is the hidden reference to the outer class (maybe even more than one). And a simple name in a method of the inner class may now be one of three things: a local, a field, or a field of an outer class.

An artifact of that complexity is that the hidden reference to the outer class can lead to memory leaks. Say the inner class is a listener and could be a static inner class. As long as the listener is registered, it holds a reference to the instance of the outer class, which may in turn hold on to large amounts of memory. Making the listener static may allow the outer instance to be garbage collected.

Renaissance answered 23/4, 2013 at 16:53 Comment(0)
P
5

A Non-static inner class has an implicit reference to outer class. If you make the class as static, you could save some memory and code.

Pengelly answered 22/4, 2013 at 12:45 Comment(0)
B
1

We already have good answers, here are my 5 cents:

Both static and non-static inner classes are used when we need to separate logical functionalities yet using the methods and variables of the outer class. Both of the inner classes have access to the private variables of the outer class.

Advantages of static inner class: 1) static classes can access the static variables from outer class 2) static classes can be treated like an independent class

Non-static inner class: 1) cannot use static members of the outer class 2) cannot be treated like an independent class

public class NestedClassDemo {
    private int a = 100;
    int b = 200;
    private static int c = 500;

    public NestedClassDemo() {
        TestInnerStatic teststat = new TestInnerStatic();
        System.out.println("const of NestedClassDemo, a is:"+a+", b is:"+b+".."+teststat.teststat_a);
    }

    public String getTask1(){
        return new TestInnerClass().getTask1();
    }

    public String getTask2(){
        return getTask1();
    }


    class TestInnerClass{
        int test_a = 10;

        TestInnerClass() {
            System.out.println("const of testinner private member of outerlcass"+a+"..."+c);
        }
        String getTask1(){
            return "task1 from inner:"+test_a+","+a;
        }
    }

    static class TestInnerStatic{
        int teststat_a = 20;

        public TestInnerStatic() {
            System.out.println("const of testinnerstat:"+teststat_a+" member of outer:"+c);
        }

        String getTask1stat(){
            return "task1 from inner stat:"+teststat_a+","+c;
        }
    }

    public static void main(String[] args){
        TestInnerStatic teststat = new TestInnerStatic();
        System.out.println(teststat.teststat_a);
        NestedClassDemo nestdemo = new NestedClassDemo();
        System.out.println(nestdemo.getTask1()+"...."+nestdemo.getTask2());
    }
}

Accessing the static inner and non-static inner class from outside:

public class TestClass {
    public static void main(String[] args){
        NestedClassDemo.TestInnerClass a = new NestedClassDemo().new TestInnerClass();
        NestedClassDemo.TestInnerStatic b = new NestedClassDemo.TestInnerStatic();
    }
}

The official java doc for static inner class can be found at https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Beane answered 7/12, 2017 at 0:13 Comment(1)
So the main reason for static inner class is to access some private static variables or private static data of the outer class? The reason shouldn't be to restrict the visibility of the class, as making it a package private class in the same directory would be good enough?Codon
K
1

Benefits of static inner classes:

  1. Instantiation of static inner class does not rely on external class guidance, and the memory overhead of instantiation.
  2. Static inner class does not hold external class guidance, does not affect the collection of external class, to avoid the extension of the external class in memory survival time leading to memory leakage.
Kerwinn answered 27/6, 2019 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.