• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unexpected output?

 
Thapliyal Akshat
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • 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
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks a lot to both of you guys for clearing this confusion.

Regards,
Akshat
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic