• Post Reply Bookmark Topic Watch Topic
  • New Topic

Initialization confusion  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't figure out why the following code outputs YXYZ.  Any help would be greatly appreciated! Thank you!

 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please always tell us where such questions come from to avoid copyright problems.

The order of initialisation is fixed by the Java® Language Specification, but you will have to search through that section to find the bit you want. Briefly, the declaration and initialisation runs first, followed by the constructor. Remember that the superclass constructor must run first.

Follow your code with a pencil and you will see you get YXYZ.
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Initialization order of an instantiation is... first, the super constructor; second, instance variables; and third, the rest of the constructor.

So... When main calls new Z, this will first call the super constructor of Z, which is the constructor of X. During the constructor call of X, this will first call the super constructor of Object. Upon completion of that, it will instantiate the instance variables of X, which is a Y instance, and will print out "Y". And then finally, to complete construction of X, it will print out "X".  Upon completion of the construction of X, which is the super of Z, it will then do the instance variables of Z, which is a Y instance, and will print out "Y". And then finally, to complete the construction of Z, it will print out "Z".

Henry
 
Bari Clark
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong: Thank you for your detailed explanation. The call to super() constructor of Object was the piece that I was missing. With that, it all makes sense.
Campbell Ritchie: Source was goCertity.com java quiz #1. Thanks for the heads up on this. I will include the source from now on.
Thank you both SO MUCH!
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleaseure
Sorry for delay in replying.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!