This week's giveaway is in the JDBC forum.
We're giving away four copies of Java Database Connections & Transactions (e-book only) and have Marco Behler on-line!
See this thread for details.
Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

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

 
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?
 
Sheriff
Posts: 13479
222
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.
 
Marshal
Posts: 64496
225
  • 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: 64496
225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done looking it up
 
Time is mother nature's way of keeping everything from happening at once. And this is a tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!