I have a base class for my all of activities (ActivityBase
) that itself derives from android.app.Activity
. In onCreate I want to execute some conditional logic based on the currently executing child class. If SomeCustomActivity
and AnotherCustomActivity
both extend ActivityBase
, how can I determine in the parent class (ActivityBase
) which of the two is the currently executing one?
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
Yes, parent and child classes can have a method with the same name.
On some occasions simply this line in the parent class solves this problem. It returns the name of the "child" class (not the parent):
this.getClass().getName() //String like "com.mycompany.myclassname" this.getClass().getSimpleName() //String like "myclassname"
See here for further discussion: http://www.coderanch.com/t/324715/java/java/Getting-child-class-name-parent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With