File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes confusion in the output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "confusion in the output" Watch "confusion in the output" New topic

confusion in the output

sharma sachin

Joined: Nov 13, 2009
Posts: 24

the output of the above program should be:
Base class Constructor
Derived class Constructor


the output of the above program is:
Base class Constructor
Derived class Constructor

can you please explain me why is it so??
because when show() of base class will be called then automatically show() of derived class will be called due to overriding mechanism but why x=0+5=5 is printing why not x=10+5=15 is printing instead of 5 please explain me i will be highly thankful to you
thank you in advance
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46367
Please use the CODE button; since you are new I have edited your post and you can see how much better it looks.

You are probably getting problems because you have two independent values for x. You have the superclass value of 90, which you never use, then you have the subclass value of 0. I think what happens is as follows:
  • Call subclass constructor, which does nothing yet.
  • Call superclass constructor.
  • Call show method: this is polymorphic so the subclass version is called.
  • The subclass x value has not been initialised, so it has its default value of 0.
  • The show method adds 5 and displays 5.
  • Superclass constructor completes and control returns to subclass constructor.
  • The value of x is initialised to 10.
  • The show method is called again and now displays 15.

  • To avoid such confusion, follow the following conventions:
  • Any methods called from the constructor should be labelled private or final.
  • Any code depending on the order of initialisation of fields is likely to give unpredictable results. Particularly if the initialisation is outside the constructor.
  • Fields are not polymorphic and not overridden: don't have subclass fields the same name as superclass fields if at all possible.
    I agree. Here's the link:
    subject: confusion in the output
    It's not a secret anymore!