I use this method for having simple access to a parent class’ functions in Java. Please note that this is not a recommended method but in case of programs with not much lines of code it becomes really helpful and easy to implement.
Let’s say you have another class somewhere in your package, or maybe it’s a subclass of the current class you are using. I’m going to assume that the parent class is called MainActivity, something common to Android.Here are the simple steps:
1. Define a static variable of the class type itself like this:
static public MainActivity main_activity;
2. In the initialization function of the same parent class assign “this” to the static variable like this:
main_activity = this;
Note : The initialization function in Android can be onCreate function.
Now you can access MainActivity class by using MainActivity.main_activity
Please also note that you need to check if the MainActivity.main_activity contains a valid class by yourself. Otherwise you may face crashes and exceptions when trying to access it.
One last thing is that this method can be used for any classes visible to each other and not just Parent and Child classes!