1. When the virtual machine loads the Java class for the first time, it initializes the static initialization block, the static member variable, and the static method once.
2. An instance of the class is created only when the new method is called
3, the class instance creation process: Initializes according to the parent-child inheritance relation, first executes the initialization block part of the parents, then constructs the method of the parent class, then executes the initialization block of the subclass that inherits from this class, and finally the constructor method of the subclass
4, when the class instance destroys, first destroys the subclass part, then destroys the parent class part
PublicClassparent{PublicStaticint t =PARENTSTATICMETHOD2 (); {SYSTEM.OUT.PRINTLN ("parent class non-static initialization block"); }Static{SYSTEM.OUT.PRINTLN ("static initialization block of parent class"); }PublicParent () {System.out.println ("constructor method for parent class"); }PublicStaticIntParentstaticmethod () {System.out.println ("static method of the parent class class")); return ten;} public static int parentStaticMethod2 () {System.out.println ("static method 2 of the parent class"); return 9;} @Override protected Void Finalize () throws Throwable { // TODO Auto-gene Rated method stub Super. Finalize (); System.out.println ("Destroy parent class");}}
PublicClass ChildExtendsparent{{System.out.println ("subclass non-static initialization block"); }Static{System.out.println ("Subclass static initialization Block")); }public child () {System.out.println ("constructor method for subclasses" ); } public static int< Span style= "color: #000000;" > Childstaticmethod () {System.out.println ("static method of the subclass" ); return 1000;} @Override protected void Finalize () throws Throwable {//< Span style= "color: #008000;" > TODO auto-generated Method stub super.finalize (); SYSTEM.OUT.PRINTLN ("Destroy sub-class"
Class test{ void// TODO auto-generated Method stub Parent.parentstaticmethod (); Child child = new Child (); }}
Output
static method for parent class 2 static method of parent class static initialization block parent class class
The static method in the class is loaded on the first call, and the static members in the class are loaded in the order in which they appear in the class. When calling static Method 2 o'clock output
static method for parent class 2 static method for parent class static initialization block parent Class 2
Comment out Parent.parentstaticmethod ();
Remove the comment child child = new Child ();
static method of parent Class 2 parent class static initialization block subclass static initialization block parent class non-static initialization block parent class constructor method for subclass non-static initialization block sub-class
Loading order of classes in Java