In java, the boot order is as follows:
1- Runs all static components in the order they are
appear as soon as the class loads into the JVM
2- Runs all instance components in the order they are
appear in the class, so an object of this class is instantiated
3- Run the constructor.
So, first the members with the reserved word static
will be executed, in the case of the informed class, were static { System.out.print("r1 "); }
, static { System.out.print("r4 "); }
and main
itself, which is also static.
Then, the class instance members were executed, in the order they appear, in the case of the displayed code, only the { System.out.print("b1 "); }
call.
Now it starts to be called the constructors, however, there is inheritance between the classes, which makes it "higher" (in this case the class Bird
) is the first to have its constructor, since the first thing a subclass does is call the constructor of its superclass, then first the constructor of Bird
will be executed, after Raptor
, finally the constructor of class Hawk
will be executed, and only after that the System.out.println("hawk ");
was displayed.
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 output 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:
link
link
link