Run the following code and observe the results:
package com.test;public class HelloB extends HelloA { public HelloB() { } { System.out.println("I'm B class"); } static { System.out.println("static B"); } public static void main(String[] args) { new HelloB(); }}class HelloA { public HelloA() { } { System.out.println("I'm A class"); } static { System.out.println("static A"); } }The results are as follows:
static Astatic BI'm A classI'm B class
Analysis:
1. Static code block: It is performed during the third step of the class loading process. The main purpose is to assign initial values to class variables.
2. Construct code block: It is independent and must be attached to the carrier to run. Java will put the construct code block in front of each construction method to instantiate some common instance variables and reduce the amount of code.
3. Constructing method: used to instantiate variables.
Summarize:
1 is at the class level, 2 and 3 are instance level, so 1 should be given priority to 2 and 3.
Their execution order is 1>2>3;
The above detailed explanation of the static code blocks, construction code blocks, and construction methods in Java is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.