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
- Waste memories as there are implicit references from
inner class
toouter 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 toouter class
- If there is a reference to the inner class object outside of the
outer class
,Inner class object
is unable to be collectedOuter class object
is unable to be collected too as it is pointed by theinner 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:
- https://code.tutsplus.com/tutorials/learn-java-for-android-development-inner-classes--mobile-3530
- https://stackoverflow.com/questions/10864853/when-exactly-is-it-leak-safe-to-use-anonymous-inner-classes/10968689#10968689
- http://stackoverflow.com/questions/10112163/inner-classes-android-vs-java
- http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class
沒有留言:
張貼留言