Hot Posts

Initialisation Blocks

The order in which initialisation blocks execute can be dificult to grasp so I present below a simple ordered list of when a block will execute.

  1. Static blocks: run when the class is loaded.
    • The class is loaded before ANY code in the class is executed.
  2. Instance blocks: run when an instance is created.
  3. You can have as many blocks as you like of both static and instance types.
  4. The order that they appear in the class determines the order in which they are executed.
  5. Instance initialisation blocks are often used as places to put code that all constructors should execute.
  6. If an exception is thrown (throw new Exception()) then it must be surrounded with a try catch, otherwise it will not compile.

It is also important to know how constructor interact with initialisation blocks. See the blog on Initialisation blocks and Constructors.

 

1 Trackback / Pingback

  1. Welcome « alex.theedom

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: