9
Hello, during my studies in Java I came across the following question
Given the code below:
class Foo extends Goo {
static {
System.out.println("1");
}
{
System.out.println("2");
}
public Foo() {
System.out.println("3");
}
public static void main(String[] args) {
System.out.println("4");
Foo f = new Foo();
}
}
class Goo {
static {
System.out.println("5");
}
{
System.out.println("6");
}
Goo() {
System.out.println("7");
}
}
I get the following output:
5
1
4
6
7
2
3
The output leads us to infer the following order of execution: static blocks and non-static blocks just before constructures. That question clarified a lot for me about the static blocks. What is not clear is the order in which classes are carried by the classloader, I thought the class Foo would have been loaded sooner because it was declared earlier, but the exit tells me that’s not how it works. Does anyone know what the rule is followed by the classloader?
I can’t answer the exact rule, but if the class
Fooinherits fromGooit is necessary thatGoobe loaded beforeFoocan "if clicked" - so the order observed.– mgibsonbr