I have code which I am unable to understand, how it produces that output. Here is the code below-
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 ");
}
}
r1 r4 pre b1 b2 r3 r2 hawk
My specific questions regarding this code are-
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?static code should be followed by non-static ones, before printing pre. Isn't it?
Hawk.main
triggers the initialization of all three classes. This is when the static intitializers run;pre
is printed;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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With