wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overrding Parent class method's Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overrding Parent class method Watch "Overrding Parent class method New topic

Overrding Parent class method's

s khosa
Ranch Hand

Joined: May 15, 2003
Posts: 72
What will be the output of the following piece of code?
class CorbaComponent
String ior;
CorbaComponent(){ startUp("IOR"); }
void startUp(String s){ ior = s; }
void print(){ System.out.println(ior); }
class OrderManager extends CorbaComponent
OrderManager(){ }
void startUp(String s)
{ ior = getIORFromURL(s); }
String getIORFromURL(String s){ return "URL://"+s; }
public class Application
public static void main(String args[])
{ start(new OrderManager()); }
static void start(CorbaComponent cc)
{ cc.print(); }
I thought the output should be "IOR", but it turns out to be "URL://IOR". Could some one please explain reason for this as to my understanding when the parent class constructor is called, startUp(string str) method called belongs to the parent class, right?
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Welcome to the Ranch sumeer.
The call "startup("IOR");" within the parent constructor is a polymorphic one: because the object being constructed is an OrderManager, the method startup in that class is called.
In fact, it is not advisable to make polymorphic method invocations to the object being constructed inside a constructor. There is a risk that the overriding method relies in the initialization of some fields declared in the class of the object being constructed, that were not initialized by the time the base constructor calls the polymorphic method.
For instance declare:
String wrong="wrong";
inside OrderManager, and modify OrderManager.getIORFromURL() to return:
return "URL://"+s+wrong;
The output is:

SCJP2. Please Indent your code using UBB Code
I agree. Here's the link: http://aspose.com/file-tools
subject: Overrding Parent class method's
It's not a secret anymore!