Java Virtual Machine class loading sequence, Java Virtual Machine Loading
When loading a class, the Java VM initializes the static variables of the parent class, initializes the static variables of the subclass, loads the parent class, and finally loads the subclass.
Public class Parent {
Static {
System. out. println ("static parent ");
}
Public Parent (){
System. out. println ("parent loaded ");
}
Public void getaaa (){
System. out. println ("parent aaa ");
}
}
Public class Child extends Parent {
Public Child (){
System. out. println ("child load ");
}
Public void getaaa (){
System. out. println ("child aaa ");
}
Static {
System. out. println ("static child ");
}
Public static void main (String [] args ){
Child child = new Child ();
Child. getaaa ();
}
}
Result:
Static parent
Static child
Parent loaded
Child load
Child aaa
Describes the process of loading classes on a Java virtual machine.
First, read the class file to JVM, find the static variable and initialize it, execute it in the static code segment, initialize the common variable, and then construct the method. Finally, load other methods.
When does the java Virtual Machine load java classes ??
Wang Sen's Java deep adventure details this issue. Generally, the jvm loads the Object class first, then the super class of the class, and then the class itself. When the class is pointed to null, the class is processed by the garbage collection mechanism, it is clear when the garbage collection mechanism is executed.
Static code blocks are initialized when classes are created or called. The concepts of being created and called are different, such as User u = new User (); at this time, u is not called, but the static module has been loaded and executed, while the User. class; this statement User does not create an instance, but is called. Static code blocks are also loaded at this time. However, the static code block is executed only once in the same application. The following is a Demo. You can check it out:
Public class User {
Static {
System. out. println ("It's a static space ");
}
Public static String name = "Jim Green ";
}
Another class is called and the main method is directly written.
Public static void main (String [] args ){
User u = new User ();
String name = User. name;
}
Here, an It's a static space will be output, and any of the comments will still be output. However, if the main method uninstalls the User, It's a static space will be output if nothing is written in the main method.