In java, the boot order is as follows:
1-Executes all static components in the order in which they
appear as soon as the class is loaded into the JVM
2-Executes all instance components in the order in which they
appear in the class, so an object of this class is instantiated
3-Executes the constructor.
Therefore, first members will be executed with the word reserved static
, in the case of the class informed, were the calls static { System.out.print("r1 "); }
, static { System.out.print("r4 "); }
and the very main
, which is also static.
Then, the instance members of the classes were executed, in the order in which they appear, in the case of the code presented, only the call { System.out.print("b1 "); }
.
Now it is beginning to call the builders, however, there is inheritance between the classes, which makes the one that is "higher" (in this case the Class Bird
) be the first to have its constructor, for the first thing a subclass does is to call the constructor of its superclass, then first the constructor of Bird
, after Raptor
, for finally the class builder Hawk
run, and only after that call System.out.println("hawk ");
was exhibited.
To better understand, I made this example:
public class TesteClasse {
public static void main(String[] args) {
new Filha();
}
}
class Pai{
static {System.out.println("Sou um membro estático da classe pai");}
public Pai(){System.out.println("Sou o construtor da classe pai.");}
{System.out.println("Sou um membro de estância da classe pai");}
}
class Filha extends Pai{
{System.out.println("Sou um membro de estância da classe filha");}
public Filha(){System.out.println("Sou construtor da classe filha");}
static{System.out.println("Sou um membro estático da classe filha");}
}
The exit is:
Sou o método main
Sou um membro estático da classe pai
Sou um membro estático da classe filha
Sou um membro de estância da classe pai
Sou o construtor da classe pai.
Sou um membro de estância da classe filha
Sou construtor da classe filha
Sou o método main de novo
See running on IDEONE.
References:
http://high5devs.com/2014/12/howto work/
http://www.javaprogressivo.net/2012/10/heranca-de-construtores-e-override.html
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
First are executed the static members(so R1, R4 and pre were the first), then follow the order of inheritance, as you well noted.
– user28595
Related http://answall.com/q/104512/101
– Maniero