Why does Android prefer static classes Why does Android prefer static classes android android

Why does Android prefer static classes


It's not just Android developers...

A non-static inner class always keeps an implicit reference to the enclosing object. If you don't need that reference, all it does is cost memory. Consider this:

class Outer {    class NonStaticInner {}    static class StaticInner {}    public List<Object> foo(){         return Arrays.asList(            new NonStaticInner(),            new StaticInner());     }}

When you compile it, what you get will be something like this:

class Outer {    Outer(){}    public List<Object> foo(){         return Arrays.asList(            new Outer$NonStaticInner(this),            new StaticInner());     }}class Outer$NonStaticInner {    private final Outer this$0;    Outer$NonStaticInner(Outer enclosing) { this$0 = enclosing; }}class Outer$StaticInner {    Outer$StaticInner(){}}


The main difference between static and non-static inner classes is that a non-static inner class has access to other members of the outer class, even if they are private. Non-static inner classes are a "part" of the outer class. You cannot create nor can they exist without an instance of an outer class. A consequence of this is that an instance of a non-static inner classes are destroyed when the outer class's instance is destroyed.

Static inner classes, on the other hand, are just like normal outer classes. The live and die on their own. You don't need an instance of the outer class for the inner class to exist. That means they also have their own life cycle. They get destroyed when the garbage collector decides to destroy them.

How does this affect memory and/or performance? I really don't know. :)


Static inner classes (i.e. classes declared inside another class with keyword static) are quite similar to "normal" classes except you don't pollute your package's name space. That is their (only) difference and benefit and I believe that's the reason you see it in Android.

Use static inner classes when the purpose of the class is tighten to the main class, but does not depend on its instances. This is generally considered as a good practice.