File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt" Watch "doubt" New topic


Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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
I have choosen as x=10 since reference is BaseClass.
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.
Tushar Kansara
I agree. Here's the link:
subject: doubt
It's not a secret anymore!