2017/02/05

Why written nested classes in Android

About

When I am working on my android project, I am quite curious about why templates from Android Studio prefers Nested classes design. After digging deeper in this issue, I believe this is worth for me to write a blog to record them down.

What is a Nested classes?

For detail please read this tutorial and this answer. Basically, Nested classes are classes defined inside of another class. For example,
class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
InnerClass is a kind of Nest classes.
There are 4 types of inner classes in general:
  • static class: declared as a static member of another class
  • inner class: declared as an instance member of another class
  • local inner class: declared inside an instance method of another class
  • anonymous inner class: like a local inner class, but written as an expression which returns a one-off object

Why using nested classes?

According to the tutorial, pros for using nested classes:
  • Able to access container’s private attributes, methods for non static inner class
  • Saves some typing in certain cases for anonymous inner class like click handlers
  • Better code organizations for related classes
  • Enhance performances in certain cases like reusing identical handlers
According to this answer and this answer, cons for using nested classes:
  • Waste memories as there are implicit references from inner class to outer class
  • High potential causing memory leaks when using non static inner class

Idea of how memory is leaked

  • Objects are unable to be garbage collected if there are references to them
  • Inner class always holds a implicit reference to outer class
  • If there is a reference to the inner class object outside of the outer class,
    • Inner class object is unable to be collected
    • Outer class object is unable to be collected too as it is pointed by the inner class object
    • This is a serious leak in android activities (outer class) as they have associated many resources like views and context etc

Words before end…

I strongly suggested you to go through the answers I pasted in this blog especially this one. The one I highlighted answering why and how memory leaks in nested class very well.

References:

沒有留言:

張貼留言