Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Android prefer static classes

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.

like image 316
Jeremy Edwards Avatar asked Jun 24 '10 02:06

Jeremy Edwards


People also ask

Why would you use a static class?

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.

What is static class in Android?

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.

Are static classes better?

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.

Why You Should Avoid static classes?

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.


1 Answers

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(){} } 
like image 158
gustafc Avatar answered Sep 28 '22 19:09

gustafc