• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance Block & Constructor

 
Veena Nair
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am having doubt about the invocation of Instance Block.
I have read like , "Instance block will be executed soon after the call to super statement from the constructor".
I have also read that " The Java compiler copies initializer blocks into every constructor."
So can anyone please help to understand how exactly is the instance block invoked and from where ?

Thank You.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The instance initializers are executed after any superclass constructors have completed and before any of the code that you put into any current class constructor is executed.

The way this is implemented (in at least some JVMs, but maybe not all) is that the compiler just copies that code into the start of each constructor (or rather, each constructor that doesn't invoke another current class constructor with this(...) as its first statement).

I think that this is the way it has to happen, because I don't think there's any such thing as an instance initializer in the bytecode. However, it's possible that this isn't actually required, and it just happens to be how it's implemented in some JVMs. You can look it up in the JVM spec and JLS yourself if you're that curious.

Regardless of that particular detail, however, the spec says when they have to execute, and the compiler and JVM are written to make sure that's what happens.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is actually strictly defined. It’s all in the Java Language Specification.
 
Veena Nair
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You Both for the valuable information.
I went through the jls , but still couldn't make out from where it get's invoked.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic