Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of Initialization Blocks

I have code which I am unable to understand, how it produces that output. Here is the code below-

Code:

class Bird {
  { System.out.print("b1 "); }
  public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
  static { System.out.print("r1 "); }
  public Raptor() { System.out.print("r2 "); }
  { System.out.print("r3 "); }
  static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
  public static void main(String[] args) {
    System.out.print("pre ");
    new Hawk();
    System.out.println("hawk ");
  }
}

Output:

r1 r4 pre b1 b2 r3 r2 hawk

Questions:

My specific questions regarding this code are-

  1. When Hawk class is instationed, it cause Raptor class to be instationed, and hence the static code block runs first. But then, static code should be followed by non-static ones, before printing pre. Isn't it?
  2. Those non-static initialization blocks seem to be actually acting like constructors. So, can these be used as constructors in regular programming?
like image 771
Prateek Singla Avatar asked Jun 07 '13 12:06

Prateek Singla


2 Answers

static code should be followed by non-static ones, before printing pre. Isn't it?

  1. Running Hawk.main triggers the initialization of all three classes. This is when the static intitializers run;
  2. pre is printed;
  3. new Hawk() triggers the execution of instance initializers for all three classes.

can these be used as constructors in regular programming?

They end up compiled together with code from constructors into <init> methods. So yes, they are similar to constructor code. The key difference is that they run regardless of which constructor runs, and run before the constructor body.

like image 118
Marko Topolnik Avatar answered Sep 19 '22 20:09

Marko Topolnik


The static blocks are run when the class is loaded therefore they run even before your method main() runs.

The initializer blocks are run before the constructors. The difference between a constructor and a initializer block is that a constractor can have parameters.

Also be aware that the initializer blocks and constructors run first in the base class and afterwards in the subclass.

like image 38
Uwe Plonus Avatar answered Sep 19 '22 20:09

Uwe Plonus