aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt" Watch "doubt" New topic
Author

doubt

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Aug 14, 2000
Posts: 38
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
------------------
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt