• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does Java Compiler Copy Initializer Blocks Into Every Constructor?  RSS feed

 
Ranjith Suranga
Greenhorn
Posts: 2
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I found this is bit confusing, I have heard & read in many times that "Java Compiler Copies Initializer Blocks Into Every Constructor".



If it is true, above code should be something like this, I guess.



and the end result would be something like this,

Initializing Block...!
Constructor 1
Initializing Block...!
Constructor 2

But in the first case result is something like this,

Initializing Block...!
Constructor 1
Constructor 2

So, "Does Java Compiler Copy Initializer Blocks Into Every Constructor"? I doubt. Is there any reference regarding this in JLS? I couldn't able to find.

Thank you.

 
Henry Wong
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
Ranjith Suranga wrote:
So, "Does Java Compiler Copy Initializer Blocks Into Every Constructor"? I doubt. Is there any reference regarding this in JLS? I couldn't able to find.


I do not believe that there is any mention of copying initializers in the Java Language Specification. The reason is likely that something like this would be an implementation detail. In other words, the JLS is for explaining the order of execution during the initialization process; and leave it up to the JVM to achieve that order.


Having said that, I too, have seen reference to this -- mostly in some older books, and/or web tutorials.  At the time, it did make sense, in that it was a good way to remember the initialization order. Of course, this memory / learning trick forgot about constructor chaining...

Henry
 
Ranjith Suranga
Greenhorn
Posts: 2
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for replying late, but thank you for your answer. It helps me to clear my doubts furthermore.

https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5

Found this lately, and it's five step process is far more clear to me, rather than thinking Java compiler copies initializer blocks into every constructor.

I think you are right, it's a memorizing trick not what actually happens.

Thank you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!