[Logo]
Forums Register Login
Question on Super
Hi,

Please look at the below code :

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.
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.
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.


Hope this helps

This thread has been viewed 894 times.

All times above are in ranch (not your local) time.
The current ranch time is
Oct 23, 2018 14:02:23.