Java’s Anonymous Inner Classes: Proceed With Caution

Java’s anonymous inner classes can be useful, but you must take care when using them. In particular: A memory leak will occur if an instance of an inner class survives longer than its containing outer class because the inner class maintains a reference to its outer class. This is not a merely academic concern, this comes up in Android development when we use inner classes to encapsulate and pass around some code, and instances of an outer class (Activities) can be constantly created and destroyed. Read more