Java class loading mechanism and java Loading Mechanism
Java class loading mechanism class Lifecycle
The lifecycle of a class includes seven stages: Loading, verification, preparation, parsing, initialization, use, and uninstallation.
Class initialization scenario 1:
When a static variable of the parent class is referenced by a subclass, the initialization process of the subclass is not caused.
The Code is as follows:
public class SSClass{ static { System.out.println("SSClass"); }} public class SuperClass extends SSClass{ static { System.out.println("SuperClass init!"); } public static int value = 123; public SuperClass() { System.out.println("init SuperClass"); }}public class SubClass extends SuperClass{ static { System.out.println("SubClass init"); } static int a; public SubClass() { System.out.println("init SubClass"); }}public class NotInitialization{ public static void main(String[] args) { System.out.println(SubClass.value); }}
Output result:
SSClass
SuperClass init!
123
Scenario 2:
The array is used to reference the class. initialization of the class is not triggered. For example, SubClass [] array = new SubClass [10]. The reason is that the bytecode instruction at this time is newarray.
Scenario 3:
When a class variable is modified by the final keyword, referencing ConstanValue does not trigger class initialization.
Cause: This constant has been stored in the constant pool in the preparation stage of the class, and the call has little to do with this class.
Application Test Questions
package com.zzjmay;public class TestJVM { public static void main(String[] args) { staticFunction(); } static TestJVM st = new TestJVM(); static { System.out.println("1"); } { System.out.println("2"); } TestJVM() { System.out.println("3"); System.out.println("a="+a+",b="+b); } public static void staticFunction(){ System.out.println("4"); } int a=110; static int b =112;}
The output result is
2
3
A = 110, B = 0
1
4
Note:
Object initializationThe step is to first initialize the member variables and then initialize the constructor
Class initializationExecute in code order. If nested object initialization exists, execute object initialization first.
Join the study exchange group 569772982 to learn and exchange.