Java class static fields, blocks, non-static fields, blocks, initialization order of constructors

Source: Internet
Author: User

Original: http://ini.iteye.com/blog/2007835

During the interview, you will often encounter such questions: give you two classes of code, they are inherited relationships, each class only constructor methods and some variables,

There may be another piece of code in the constructor that does some arithmetic on the value of the variable, plus some code that outputs the value of the variable to the console, and then lets us determine the output
Results. This is actually a look at our understanding of the initialization order of classes in the case of inheritance.
As we all know, for static variables, static initialization blocks, variables, initialization blocks, constructors, they are initialized in order to be
(Static variables, static initialization blocks) > (variables, initialization blocks) > constructors.
We can also verify this with the following test code:
Java code

Java code
 Public classInitialordertest {//Static Variables     Public StaticString Staticfield = "Static variable"; //variables     PublicString field = "Variable"; //Static initialization blocks    Static{System.out.println (Staticfield); System.out.println ("Static initialization Block"); }                      //Initialize block{System.out.println (field); System.out.println ("Initialize block"); }                      //Constructors     Publicinitialordertest () {System.out.println ("Constructor"); }                       Public Static voidMain (string[] args) {Newinitialordertest (); }          }  

Running the above code, we will get the following output result:
static variables
Static initialization blocks
Variable
Initialize block
Constructors
This is in full conformity with the above mentioned.
So what happens to the inheritance? We still get the final result with a test code:
Java code

Java code
classParent {//Static Variables     Public StaticString P_staticfield = "Parent class--Static variable"; //variables     PublicString P_field = "Parent class--variable"; //Static initialization blocks    Static{System.out.println (P_staticfield); System.out.println ("Parent class--static initialization block"); }                      //Initialize block{System.out.println (P_field); System.out.println ("Parent class--initialization block"); }                      //Constructors     PublicParent () {System.out.println ("Parent class--constructor"); }         }                   Public classSubclassextendsParent {//Static Variables     Public StaticString S_staticfield = "Subclass--Static variable"; //variables     PublicString S_field = "Subclass--Variable"; //Static initialization blocks    Static{System.out.println (S_staticfield); System.out.println ("Subclass--Static initialization block"); }              //Initialize block {System.out.println (S_field); System.out.println ("Subclass--Initialization block"); }                      //Constructors     PublicSubclass () {System.out.println ("Subclass--constructor"); }                      //Program Entry     Public Static voidMain (string[] args) {Newsubclass (); }          }  

Run the above code, and the results will immediately appear in front of us:

Parent class--Static variable
Parent class--static initialization block
Subclass--Static variables
Subclass--Static initialization block
Parent class--variable
Parent class--initialization block
Parent class--constructor
Subclass--Variables
Subclass--Initialization block
Sub-class--constructor
Now, the results have been self-evident. One thing you might notice is that the initialization of subclasses is not done until the parent class is fully initialized.
In fact, the initialization of the static and static initialization blocks of a subclass is done before the parent class's variables, initialization blocks, and constructors are initialized.
What about the sequence between static and static initialization blocks, variables, and initialization blocks?
Is the static variable always initialized before the static initialization block, and the variable always initializes before the initialization block? In fact, it depends on the order in which they appear in the class.
We describe static variables and static initialization blocks as examples. Again, let's write a class to test:

Java code

Java code
 Public classTestorder {//Static Variables     Public StaticTestA A =NewTestA (); //Static initialization blocks    Static{System.out.println ("Static initialization Block"); }                           //Static Variables     Public StaticTestb B =NewTestb ();  Public Static voidMain (string[] args) {NewTestorder (); }          }                  classTestA { PublicTestA () {System.out.println ("Test--a"); }          }                  classTESTB { PublicTestb () {System.out.println ("Test--b"); }          }  

Running the above code, you will get the following result:

Test--a
Static initialization blocks
Test--b
You can change the position of variable A, variable B, and the static initialization block at will, and you'll see that the output changes as they appear in the class.
This means that static variables and static initialization blocks are initialized in the order in which they are defined in the class. Similarly, variables and initialization blocks follow this pattern.
After understanding the initialization order of the classes under inheritance, how to determine the final output is solved.

Test function:

Java code
 Public classTeststaticcon { Public Static intA = 0; Static{a= 10; System.out.println ("The static code block of the parent class is executing a=" +a); } {a= 8; System.out.println ("The non-static code block of the parent class is executing a=" +a); }         PublicTeststaticcon () { This("A in the parent class with the parameter in the constructor method of the value:" + Teststaticcon.a);//call a different constructor methodSystem.out.println (a); System.out.println ("Parent class no parameter construction method in execution a=" +a); }         PublicTeststaticcon (String N) {System.out.println (n);        System.out.println (a); }         Public Static voidMain (string[] args) {Teststaticcon TSC=NULL; System.out.println ("!!!!!!!!!!!!!!!!!!!!!"); TSC=NewTeststaticcon (); }  }  

Operation Result:

A non-static block of code for the parent class is executing a=10
!!!!!!!!!!!!!!!!!!!!!
A non-static block of code for the parent class is executing a=8
A value in the parent class with parameter construction method: 10
8
8
The parent class no-parameter construction method performs a=8


Conclusion: Static code blocks are executed automatically when the class is loaded, and non-static code blocks are code that executes automatically when the object is created, and does not create objects that do not execute non-static blocks of code for that class. And the execution order is static code block------Non-static code block----constructor.
Extensions: Static code blocks vs. static methods:
In general, if some code must be executed when the project is started, you need to use static code block, this code is active;
It needs to be initialized at the start of the project, and when the object is not created, the static method is used when the other program calls it, and the code is executed passively.
The difference between the two is: static code blocks are automatically executed; Static methods are executed only when they are called.

function: Static code blocks can be used to initialize some of the most common variables or objects in a project; static methods can be used as code that does not create an object or may need to be executed

Ali written Questions:

Ask for the output of this code:

Java code
 Public classTest1 { Public Static intK = 0;  Public StaticTest1 T1 =NewTest1 ("T1");  Public StaticTest1 t2 =NewTest1 ("T2");  Public Static inti = print ("I");  Public Static intn = 99;  Public intj = Print ("J"); {Print ("Building Blocks"); }            Static{print ("Static Block"); }         PublicTest1 (String str) {System.out.println (++K) + ":" +str+ "i=" +i+ "n=" +N); ++i;++N; }             Public Static intprint (String str) {System.out.println (++K) + ":" +str+ "i=" +i+ "n=" +N); ++N; return++i; }             Public Static voidMain (string[] args) {//TODO auto-generated Method StubTest1 T =NewTest1 ("Init"); }    }  

Operation Result:

1:j i=0 n=0
2: Construction block I=1 n=1
3:t1 i=2 n=2
4:j i=3 n=3
5: Construction Block i=4 n=4
6:t2 i=5 n=5
7:i i=6 n=6
8: Static block i=7 n=99
9:j i=8 n=100
10: Construction Block i=9 n=101
11:init i=10 n=102

Java class static fields, blocks, non-static fields, blocks, initialization order of constructors

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.