classparent{StaticString name = "Hello"; {System.out.println ("3 Parent Block"); } Static{System.out.println ("1 Parent static block"); } PublicParent () {System.out.println ("4 Parent constructor"); } } classChildextendsparent{StaticString childname = "Hello"; {System.out.println ("5 Child Block"); } Static{System.out.println ("2 Child static Block"); } PublicChild () {System.out.println ("6 Child constructor"); } } Public classStaticiniblockordertest { Public Static voidMain (string[] args) {NewChild ();//statement (*) } }
Results:
1 Parent Static block
2 Child static Block
3 Parent Block
4 Parent constructor
5 Child Block
6 Child constructor
2. Order:
1) Executes the static content of the parent class, after the static content of the parent class executes, then executes the static content of the subclass;
2) When the static content of the subclass is finished, then to see if the parent class has no non-static code block, if there is a non-static block of code to execute the parent class, the non-static code block of the parent class executes, then executes the parent class construction method;
3) After the construction method of the parent class executes, it goes on to see if the subclass has no non-static block of code, and if there is a non-static block of code that executes the subclass. The non-static code block of the subclass executes and then executes the subclass's construction method.
In short, the static code block content executes first, then executes the parent class non-static code block and construction method, then executes the subclass non-static code block and constructs the method.
and the construction method of the subclass, regardless of the constructor method with no parameters, the default it will first look for the parent class without parameters of the construction method. If the parent class does not have a constructor with no arguments, the subclass must use the supper key to call the parent class with the constructor of the parameter, otherwise the compilation cannot pass.
Java Static statement block, statement block, constructor execution order