File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assigning sub class reference to super class object 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 "Assigning sub class reference to super class object" Watch "Assigning sub class reference to super class object" New topic
Author

Assigning sub class reference to super class object

Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
Pls check this code:
==========================================
class Base{
void methodA(){
System.out.println("methodA");
}
}

class Sub extends Base{
void methodB(){
System.out.println("methodB");
}

public static void main(String a[]){
Base oBase = new Sub();
oBase.methodB(); //causing the error
}
}
===========================================
Here, even I have created base object, assigning the reference of Sub. Now why I am not able to call a methodB() which is exisitn in Sub class???
When I put the methodB() in Base class its workign fine.


Javardhan:
Sandeep Prabhakar
Ranch Hand

Joined: Dec 22, 2005
Posts: 59
Hey,
Consider this segment of code

public static void main(String a[]){
Base oBase = new Sub();
oBase.methodB(); //causing the error
}
}
Now, since oBase is declared to be a reference to an object of Base, all that the compiler knows is methodA() (even though u r assigning a child class reference which happens only at runtime) and hence the error.
To overcome this, one way would be to have a dummy method named methodB in base. Hope this would be helpful.
Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
Sandeep- Thanks for your reply.
Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
Sandeep- Thanks for your reply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assigning sub class reference to super class object