I see a lot of java code where android prefers to have developers use static inner classes. Particularly for patterns like the ViewHolder Pattern in custom ListAdapters.
I'm not sure what the differences are between static and non-static classes. I've read about it but it doesn't seem to make sense when concerned with performance or memory-footprint.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.
A "static class" is an inner class that doesn't require an instance of its enclosing class, which has nothing to do with sharing application-wide data.
Static classes and static members are useful because they do not require instances created for each new object. That means, they consume fewer resources and no duplication of the same class or member is needed in memory. Static members make code cleaner.
Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.
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(){} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With