Avoid using non-static inner classes in an activity if instances of the inner class could outlive the activity’s lifecycle.
- In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.
- Instead, prefer static inner classes and hold a weak reference to the activity inside.
- Use the following code to avoid leaking the Activity and its Context.
Declaration -> private static class MyHandler extends Handler
Inner class attribute -> WeakReference<Activity> act;
Inner class instantiation -> act = new WeakReference<Activity>(activity);
Inner class reference -> Activity activity = act.get();
Final, Finally, Finalize
- final attribute is when the variable reference cannot be changed and becomes a constant.
- final method is a method that cannot be overridden.
- final class is a class that cannot be inherited or extended.
- in a try – catch block, the finally block is for any cleanup required in the code that got executed from the try block when the exception occurred.
- This is a class method that is called when the object is ready for but right before garbage collection for cleanup.