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

Why didn't the static block got called?  RSS feed

 
Vaibhav Sagar
Ranch Hand
Posts: 35
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, could anyone help me understand why the following code prints only "Parent" and not "Parent Child"?


Why didn't the JVM load the Child class and only loaded the Parent class?
 
Junilu Lacar
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting. I suppose the compiler is able to determine that only the Parent class is needed to execute line 12.
 
Campbell Ritchie
Marshal
Posts: 55711
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It goes to show the difference between static and instance methods. An instance method would be polymorphic and the subclass method would be called, but that doesn't apply if it is static. If you change that field to an instance field you get both initialisers executed. I shall let you work out which order.
 
Vaibhav Sagar
Ranch Hand
Posts: 35
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. I also found that JLS says that this is correct behavior, https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#d5e14527
I found it kinda counter intuitive at first but it does make sense and is the right thing to do by the compiler.

Ordering in case of instance intialisers would be from superclass to subclass.
 
Campbell Ritchie
Marshal
Posts: 55711
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done looking it up
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!