wood burning stoves
The moose likes Beginning Java and the fly likes Instance Block & Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Instance Block & Constructor" Watch "Instance Block & Constructor" New topic

Instance Block & Constructor

Veena Nair

Joined: Jul 08, 2012
Posts: 13
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

Joined: Jan 03, 2004
Posts: 6109

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

Joined: Oct 13, 2005
Posts: 46389
It is actually strictly defined. It’s all in the Java Language Specification.
Veena Nair

Joined: Jul 08, 2012
Posts: 13
Thank You Both for the valuable information.
I went through the jls , but still couldn't make out from where it get's invoked.
I agree. Here's the link: http://aspose.com/file-tools
subject: Instance Block & Constructor
It's not a secret anymore!