Static blocks, heritage and constructors in Java

Asked

Viewed 450 times

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 Foo inherits from Goo it is necessary that Goo be loaded before Foo can "if clicked" - so the order observed.

2 answers

7


To language specification gives a hint. Let’s analyze step by step.

In the class load the static boot block is called.

First flame Goo (prints "5") which is required for use in Foo (can’t run something before its dependency)

Then the block of Foo is executed (prints "1").

Executes the main() (prints "4") and instance a type variable Foo.

Executes initialization of the instance of Goo first (prints "6" and "7") for later use in Foo, since without Goo exist before Foo cannot exist. Executes both the instance initialization block and the constructor.

Foo then is instantiated (prints "2" and "3").

3

According to documentation from Oracle. 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, the 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.

Concept of Initialization

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.