Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Super

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mathias Nilsson
Ranch Hand
Posts: 367
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mathias Nilsson
Ranch Hand
Posts: 367
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hope this helps
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic