Forums Register Login

confusion in the output

+Pie Number of slices to send: Send





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

but

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

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
+Pie Number of slices to send: Send
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 have a knack for fixing things like this ... um ... sorry ... here is a consilitory tiny ad:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com


    reply
    reply
    This thread has been viewed 743 times.
    Similar Threads
    why the output is so?
    confusion in output
    Constructors
    question from Sahir's Mock Exam
    Overriden methods and contructor chaining
    More...

    All times above are in ranch (not your local) time.
    The current ranch time is
    Mar 29, 2024 08:24:19.