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 Unexpected output? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Unexpected output?" Watch "Unexpected output?" New topic

Unexpected output?

Thapliyal Akshat

Joined: Jun 04, 2009
Posts: 29
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,
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
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.

JDBCSupport - An easy to use, light-weight JDBC framework -
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46368
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

Joined: Jun 04, 2009
Posts: 29
Thanks a lot to both of you guys for clearing this confusion.

I agree. Here's the link:
subject: Unexpected output?
It's not a secret anymore!