Initialization order in Java

Source: Internet
Author: User
/**
 * 1, when using a new object instance or calling a static member variable or method, initialize the static variable
 * 2, the static variable is initialized first in the initialization, the static block and the static variable are treated identically (during initialization, when there is a new object instance, Temporarily stop the static variable initialization after)
 * 3, when a static variable is not initialized, the default initial value (such as int 0)
 * 4, a new object instance is assigned to a non-static member variable, and so does the building block, which is preceded by the initialization of
 * 5, When a member variable is not initialized, use the default initial value (such as int 0)/public
class Testinit {
	private int i = print ("Member variable Assignment");
	{
		print ("Building block");
	}
	private static int J = Print ("Static variable Assignment");
	static {
		print ("static block");
	}
	private static Testinit ti1 = new Testinit ("Ti1");
	private static int k = 0;
	Public Testinit (String str) {
		System.out.println ("K:" + ++k + "	" + str + "	I:" + i++);
	}
	private static Testinit Ti2 = new Testinit ("Ti2");
	
	private static int print (String str) {
		System.out.println ("K:" + ++k + "	" + str + "	J:" + j + +);
		return j;
	}
	
	public static void Main (string[] args) {
		new Testinit ("Init");
	}


Results:

K:1	static variable assignment	j:0
k:2	static block	j:1
k:3	member variable assignment j:2 k:4	construction block	j:3
k:5	ti1	i:3
k:1	member variable assignment	j:4
k:2	construction block j:5
k:3 ti2 i:5 k : 4	member variable assignment	j:6
k:5	construction block	j:7
k:6	init	i:7


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.