• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Help me

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hai,
class SuperClass
{
int superValue;
SuperClass()
{
System.out.println("Constructor of SuperClass");
this.doValue();
}
public void doValue()
{
this.superValue=555;
System.out.println("superValue= "+this.superValue);
}
}
class SubClass extends SuperClass
{
int value=800;
SubClass()
{
System.out.println("Constructor of SubClass");
this.doValue();
System.out.println("superValue= "+this.superValue);
}
public void doValue()
{
System.out.println("value= "+this.value);
}
public static void main(String arg[])
{
SuperClass a=new SubClass();
}
}
I found this program in this discussion area.The output of this is
Constructor of SuperClass
value=0
Constructor of Subclass
value=800
superValue=0
After printing "Constructor of SuperClass" ,why is it executing doValue() method of SubClass instead of executing SuperClass's doValue() method.
Can anyone help me at this
Thanks

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
doValue() from subclass gets excecuted b'cos-overriding of methods in Java always takes into account the "content" of the object ref. variable & not the type.
In this case,
Superclass a=new Subclass();
"a" is of TYPE Superclass ,but it's CONTENT is a ref value of the Subclass.Hence,ALWAYS the doValue() from Subclass is executed and not that of the base(Superclass) class.
Good Luck!
 
Beauty is in the eye of the tiny ad.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic