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
public class parent{public static int t = PARENTSTATICMETHOD2 (); { System.out.println ("Parent class non-static initialization block"); } Static { System.out.println ("The parent class statically initializes the Block"); } Public parent () { System.out.println ("constructor method for parent class"); } public static int Parentstaticmethod () { 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-generated method stub Super.finalize (); System.out.println ("Destroy parent Class"); } }
public class Child extends parent{ { 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 Childstaticmethod () { System.out.println ("static method of the subclass"); return; } @Override protected void Finalize () throws Throwable { //TODO auto-generated method stub Super.finalize (); SYSTEM.OUT.PRINTLN ("Destroy sub-Class");} }
public class test{public static void Main (string[] args) { //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
Java Class load Order