A static block of code
- There can be output statements inside.
- Loaded as the class loads, and is only loaded once
- Multiple static code blocks executed in sequential structure
- Static code blocks are executed before the execution of non-static code blocks.
- Static structures (class properties, class methods) can only be executed in a block of code
Second, non-static code block
- You can initialize the properties of a class (Static & Non-static), and you can invoke methods of the declaration of this class (Static & Non-static)
- There can be output statements inside.
- There can be more than one non-static block of code in a class, and multiple code blocks are executed in a sequential structure
- Every object that creates a class, a non-static block of code is loaded once
- Non-static code blocks are executed earlier than the constructor
Note: If the code block is modified, you can only use the static
PackageCom.yyx.pratice;classRoot {Static{System.out.println ("Static initialization block of root"); } {System.out.println ("Root's normal initialization block"); } PublicRoot () {System.out.println ("Root parameterless constructor"); }}classMidextendsRoot {Static{System.out.println ("Static initialization block for mid"); } {System.out.println ("Normal initialization block for mid"); } PublicMid () {System.out.println ("No parametric constructor for mid"); } PublicMid (String msg) {//calling overloaded constructors in the same class through this This(); System.out.println ("Mid with parametric constructor, its parameter value:" +msg); }}classLeafextendsMid {Static{System.out.println ("Static initialization block of the leaf"); } {System.out.println ("Plain initialization block of the leaf"); } PublicLeaf () {//A constructor that invokes a string argument in the parent class through Super Super("Still Silicon Valley"); System.out.println ("The constructor that executes the leaf"); }} Public classTestleaf { Public Static voidMain (string[] args) {NewLeaf (); System.out.println (); NewLeaf (); }}
Operation Result:
Static initialization block of root
Static initialization block for mid
Static initialization block of the leaf
Common initialization block for root
The parameterless constructor of root
Normal initialization block for mid
Parameter-free constructors for mid
The parametric constructor for mid, with its parameter values: still Silicon Valley
Ordinary initialization blocks of the leaf
The constructor that executes the leaf
Common initialization block for root
The parameterless constructor of root
Normal initialization block for mid
Parameter-free constructors for mid
The parametric constructor for mid, with its parameter values: still Silicon Valley
Ordinary initialization blocks of the leaf
The constructor that executes the leaf
Java code block