Win a copy of Spring Boot in Practice this week in the Spring 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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
------------------
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic