Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Please explain the output of my code.  RSS feed

 
Vector Sanasam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanted to know the order at which static blocks, instance blocks and constructors run. So i wrote this code but could not understand the output completely. Could someone explain it to me.

 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37230
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If that's the only code, it prints an error message because there is no main method. Assuming you have a main method that instantiates the object, the output is:



This tells you that static blocks are initialized first. Then instance initializers (the code in the curly brackets without being in a method.) Then the constructor runs after both of those.
 
Vector Sanasam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the output is this:
 
Vector Sanasam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a main method at line 27. If your java compiler cant see public static void main(String... a) as the main method signature change it to public static void main(String[] a)
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37230
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both public static void main(String... a) and public static void main(String[] a) have been equivalent since Java 5 so that's not a problem.

Now that the program is longer, how about you say which part of the output you don't understand?
 
Vector Sanasam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain to me the output from line 4 to 9 (from the output which i gave)
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37230
519
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This output (below) shows that static blocks run first and the superclass one runs before the subclass one. It also shows that for instance initializers and constructors, they run from superclass to subclass in that order.

SUPER_CLA static initializer block
CLA static initializer block
SUPER_CLA instance initializer block
SUPER_CLA constructor
CLA instance initializer block
CLA constructor
 
Vector Sanasam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, now i understand.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!