• Post Reply Bookmark Topic Watch Topic
  • New Topic

When is a variable initialised?  RSS feed

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code the print method prints the default value of int(zero) for the first time even when the variable i has been assigned a value of 4. Why? A detailed explanation is appreciated.



Output:
Inside constructor of A1()
0
Inside constructor of B1()
4
 
Marshal
Posts: 56600
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the Java Language Specification (=JLS) which gives the order things happen in.
Before the body of the B constructor runs, the whole of the superclass constructor runs. The class A is initialised and then the print method is called. Because of polymorphism the B version is used. At that point the B initialisation process is incomplete, so you get 0. You will have to look carefully at the JLS link I gave you to confirm whether this printing 0 is required and consistent behaviour or not.

Lesson: methods called from inside a constructor should be final or private to avoid this sort of problem.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!