• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • 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!
 
Tushar Kansara
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • 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
------------------
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic