Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child class name from parent

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?

like image 483
Rich Avatar asked Mar 03 '11 03:03

Rich


People also ask

Can a parent class reference a child class?

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.

Can a parent class access child class 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.

Can child class have same method name as parent class?

Yes, parent and child classes can have a method with the same name.


1 Answers

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

like image 117
OneWorld Avatar answered Oct 21 '22 14:10

OneWorld