Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Question on Super  RSS feed

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • 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.
 
Ranch Hand
Posts: 367
  • 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
  • Mark post as helpful
  • 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
  • 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
Boost this thread!