• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Unexpected output?

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Guys,

I am having small problem in the below program. Why the call method of class B is not invoked?
After running this program the output that comes is b = 0 b = 16 which is out of my expectation.

Instantiating the Object of A will call B() using super() as parent has to exist before a child comes into existence.
How the call() of A is invoked instead of call() of B.



Kindly clear the muddle of clouds???

Thanks and Regards,
Akshat
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please put your code in the code tags. Makes things easier for me .

When instantiating A, the compiler is so kind and puts 'super()' as the first statement in the constructor. You got that part correct.
Now, the B constructor calls 'call()', which is polymorphically (since you instantiated A) delegated to the concrete class, so the B constructor calls 'call()' on the A class.
The value 0 goes to the output since instance variables get initialized after the super constructor ran, hence b is still 0.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Apart from the fact that calling methods from the constructor can be dangerous (unless they are labelled "private" or "final") . . .


What you have here is an example of polymorphism. You create an A and it invokes the "A" version of the method. That demonstrates that calling method from the constructor can be dangerous; you don't know what they are going to do.
 
Thapliyal Akshat
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot to both of you guys for clearing this confusion.

Regards,
Akshat
 
reply
    Bookmark Topic Watch Topic
  • New Topic