Hi, I have a superclass which is extended by 'N' number of classes. Now I have modified a method in the superclass to get the name of the calling subclass. Is there any way through which my superclass method shall get its subclasses class name?
(Note: I can't modify my subclasses code; I can only modify the existing method written in the superclass which is called by all other subclasses.)
Here when class B,C & D is executed, it calls the super class method displayClass() and it should print the name of the respective class which is calling the method i.e., Class B,C & D respectively.
Can anybody tell me how will I achieve this in the superclass method displaClass() without overriding the method in the subclass or passing anything as argument to the superclass method i.e., without touching the code in the subclasses?
Thanks in advance.
The Next Best Thing To Knowing Something Is Knowing Where To Find It.
The method getClass(), inherited by every class from java.lang.Object, returns the Class object representing the object on which the method is called. The Class object has a getName() method that returns the name of the class. So your displayClass() method can call getClass(), and then getName() on the Class object, to get the name of the class of the object it finds itself in.