java is a static language (first compiled, then executed), but it also has many of the characteristics of dynamic languages. java class loading, is connected, during operation of the program initialization is completed.
- Load: loads the class files compiled into memory. There are loads of ways
- Load class files directly from the local system
- Load class files remotely over the network
- Load class files from the zip, jar in
- Dynamically loaded into class files, with reference to the source file during program run java dynamic proxy design pattern
- Connection: connection divided into three stages
- Verification: Verify that the class files that match jvm specification as class files can be artificially tampered with.
- Preparation: static variables of the class allocates memory space, and assign default values. (Such as the default value of int is 0, the default value of the referenced object is null)
- Analysis: Symbol reference into a direct reference.
- Initialization: static class variable assignment; performing static class code block static {}
Initialization scene class: class when active references will perform initialization, the following scenario is an active reference to the class
- Create an instance of the class, create an object that is
- Static variables to access or modify the class
- Static method call class
- reflection
- Initializing a subclass of class (will first initialize the parent class)
/** * Created by IntelliJ IDEA. * User: chenzhubing * Date: 2019/6/16 */ public class ClassInitTest { public static void main(String[] args) { System.out.println(Child.str1); } } class Parent{ static String str1 = "hello"; static{ System.out.println("parent static block....."); } } class Child extends Parent{ static String str2 = "world"; static{ System.out.println("child static block......."); } }
Analysis:
- Access Child.str1 performs initialization class, static code execution classes will block content
- For static variables, only directly define the class of the variable will be initialized. So Child class does not perform the initialization
- Output:
parent static block.....
hello
/** * Created by IntelliJ IDEA. * User: chenzhubing * Date: 2019/6/16 */ public class ClassInitTest { public static void main(String[] args) { System.out.println(Child.str2); } } class Parent{ static String str1 = "hello"; static{ System.out.println("parent static block....."); } } class Child extends Parent{ static String str2 = "world"; static{ System.out.println("child static block......."); } }
Analysis:
- Access Child.str2 executes initialization Child class, because it inherits Parent, Parent and therefore will first perform initialization
- Output:
parent static block.....
child static block.......
world