• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overrding Parent class method's

 
s khosa
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
URL://IORnull
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic