• 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:

doubt

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Anyone please explaine me about the o/p of this program:
class BaseClass{
int x = 10;
public void aMethod(){
System.out.println("x = "+x);
}
}

class SubClass extends BaseClass{
int x = 20;
public void aMethod(){
System.out.println("x = "+x);
}
public static void main(String [] arg){
BaseClass bc = new SubClass();//1
bc.aMethod();
}
}
o/p:x=20
I have choosen as x=10 since reference is BaseClass.
Thanks!
 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is one of the most basic concept in Object Oriented Programming.
Understand that the variable BaseClass bc is a variable which is declared of Type baseClass. But it points to an object of type Subclass.
this is called as referencing of objects.
The variable is pointing to Sub Class & not base class.
Hence when you invoke the aMethod, which incidentally you have overridden in the sub class will be invoked.
Also note that with the same code above, & no overridden method in sub class, the method in the base class will be invoked, since sub class inherits methods from the Super class, unless it is declared private.
Regards
Tushar Kansara
------------------
 
Today you are you, that is turer than true. There is no one alive who is youer than you! - Seuss. Tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic