class Parent { public void Method() { System.out.println(this.getClass().getName()); } } public class Child extends Parent { public void Method() { super.Method(); System.out.println(this.getClass().getName()); } public static void main(String[] args) { Parent p = new Parent(); p.Method(); Child c = new Child(); c.Method(); } }
Now the output I was expecting : Parent Parent Child
But actually what I'm getting is Parent Child Child
Does the call to the overridden Method(), not invoke the parent class's Method(). Even though the actual call is made on the object of Child, because of the keyword super, do not we get the name of the Parent class displayed from the Child's Method().
Please clarify on this.
Mathias Nilsson
Ranch Hand
Joined: Aug 21, 2004
Posts: 367
posted
0
Hi! This is taken from the api
getClass public final Class getClass()Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Returns: the object of type Class that represents the runtime class of the object.
This will get you the result you are looking fpr.
SCJP1.4
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Thanks Mathias. But what if I need to display the name of the Parent class within a method of a Child class. Do I need to create an object of Parent class in the child object and invoke getClass().getName() method. Is there any other way of getting the desired output.