Static Blocks, Inheritance, and Constructors in Java

8

Hello, during my studies in Java I came across the following doubt

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 the constructs. This question has clarified a lot for me about static blocks. What is not clear is the order in which the classes are loaded by the classloader, I thought that the class Foo would be loaded before because it is declared before, but the output tells me that this is not how it works. Does anyone know what the classloader rule is?

    
asked by anonymous 17.12.2015 / 17:39

2 answers

7

language specification gives a hint. Let's look at it step by step.

In class loading the static boot block is called.

First call Goo (print 5) that is required for use in Foo (can not execute something before its dependency)

Then the Foo block is executed (prints 1).

Executes main() (prints 4) and instantiates a variable of type Foo .

Performs the initialization of the instance of Goo first (prints 6 and 7) for later use in Foo , since no Goo exists before Foo can not exist. It runs both the instance initialization block and the constructor.

Foo is then instantiated (prints 2 and 3).

    
17.12.2015 / 18:12
2

According to the Oracle documentation. In Chapter 12 it says:

  

Before a Class is initialized, its Direct Superclass must be initialized, but the Interfaces implemented by the Class are not initialized. Similarly, Superinterfaces of an Interface are not initialized before the interface is initialized.

Original:

  

Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class are not initialized. Similarly, the superinterfaces of an interface are not initialized before the interface is initialized.

Initialization Concept

Initialization of a Class consists of executing its static initializers and initializers for static fields (class variables) declared in the class.

Initializing an interface consists of running the initializers for fields (constants) declared in the interface.

    
17.12.2015 / 18:08