JAVA class and instance initialization process initialization process

Class initialization (static part)

Clinit execution method 

  1. main method of  the class where the need to load and initialize
  2. Initialize the subclass need to initialize the parent class
  3. Class is initialized to point <clinit> () method
    ①, <clinit> () method by a static  display variable assignment class codes  and the static block of code  consisting
    ②, class variables and display a static code block codes assigned codes
    from top to bottom order execution (< cliinit> () execution order) of the method
    ③, <clinit> () method  is executed only once

Examples initialized (non-static part)

Examples of initialization performed <init> method (i.e., the above initialization clinit class)

  1. <Init> () method may have a plurality of overload, there are several constructors have several <init> method
  2. <Init> () method to display an assignment code blocks by the block non-static and non-static instance variables, configuration code corresponding to the composition
  3. Non-static instance variables and display the code assignment block non-static sequential execution of code from top to bottom, corresponding to the last configuration code execution
  4. Each create an instance, call the corresponding constructor is performed corresponding <init> () method
  5. First line <init> () method is super () or super (argument parameter list) corresponding to the parent class <init> () method

 Byte code file:

Analysis examples:

What are the main method to perform the following outputs Son class?

Father.java file

public class Father{
	private int i = test();
	private static int j = method();

	static{
		System.out.print("(1)");
	}
	Father(){
		System.out.print("(2)");
	}
	{
		System.out.print("(3)");
	}


	public int test(){
		System.out.print("(4)");
		return 1;
	}
	public static int method(){
		System.out.print("(5)");
		return 1;
	}
}

Son.java files execute the following code will output what?

public class Son extends Father{
	private int i = test();
	private static int j = method();
	static{
		System.out.print("(6)");
	}
	Son(){
//		super();//写或不写都在,在子类构造器中一定会调用父类的构造器
		System.out.print("(7)");
	}
	{
		System.out.print("(8)");
	}
	public int test(){
		System.out.print("(9)");
		return 1;
	}
	public static int method(){
		System.out.print("(10)");
		return 1;
	}
	public static void main(String[] args) {
//		Son s1 = new Son();
//		System.out.println();
//		Son s2 = new Son();
	}
}

result

发布了242 篇原创文章 · 获赞 13 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/103975485