In what order do static/instance initializer blocks in Java run?

前端 未结 8 1574
心在旅途
心在旅途 2020-11-22 17:01

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in

相关标签:
8条回答
  • 2020-11-22 17:51

    http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

    kindly check java documentation.

    then clearly mentioned no matter how may static blocks are there they will be executed as a single block in the order they appear

    So,

    My understanding here is java is looking your code as

    static{
    i=1;
    i=2;
    }
    

    static int i;

    that is why you are getting output 2

    hope this is helpful

    0 讨论(0)
  • 2020-11-22 17:53

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

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

    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.

    0 讨论(0)
提交回复
热议问题