Initialization process for Java objects (static members, static code blocks, common code blocks, construction methods)

Source: Internet
Author: User

First, the Java object initialization process

 The first step is to load the class , where a Java object will load class before initialization, generating class objects in the JVM. Loading a class will do the following, giving a recursive description below. ( for a class object see reflection click here)

If the class has a parent class, the parent class is loaded first.

I initialize the static members of the class

II execute this type of static code block

  The second step, creating the object , if the class has a parent class, creates an object of its parent class, wraps the properties and methods of the child class, and then returns a reference to the subclass, giving a recursive description below.

If the class has a parent class, the object of the parent class is created first.

I initialize the ordinary members of the class.

II Execute the normal code block.

III calls the class construction method.

Second, the case test

The class object acts as a member variable

 Public class info{    public  Info (String s) {        System.out.println (s);    }}

Parent class

 Public classParent { Public StaticInfo info =NewInfo ("Parent static member");//Static Members          PublicInfo Info2 =NewInfo ("Parent common member");//Ordinary Members        Static{//Static code blockSYSTEM.OUT.PRINTLN ("Parent static block"); }        {                                                                //Common code blocksSYSTEM.OUT.PRINTLN ("Parent Common block"); }         PublicParent () {//Parent Class Construction MethodSystem.out.println ("Parent.parent ()"); }}

Sub-class

 Public classChildextendsparent{ Public StaticInfo info =NewInfo ("Child static member");//Static Members         PublicInfo Info2 =NewInfo ("Child common member");//Ordinary Members        Static{//Static code blockSYSTEM.OUT.PRINTLN ("Child static Block"); }        {                                                                //Common code blocksSYSTEM.OUT.PRINTLN ("Child Common Block"); }         PublicChild () {//sub-class construction methodsSystem.out.println ("Child.child ()"); }}

The following test class loading process, we do not create the object, but directly load the class, and is loaded subclass

 Public classinitobjecttest{ Public Static voidMain (string[] args) {Try{            //class.forname ("Parent");Class.forName ("Child"); }Catch(Exception e) {}//System.out.println ("=============== Now, we create an Object below ==========="); //new Parent ();    }}

Test results:

The test results conform to the rules of the load class written above, first initialize the parent class static member, then execute the parent class static block, then initialize the child class static member, and finally execute the subclass static block. We can see that the static members are actually initialized when the class loads.

Note: The class is loaded only once, and then the created object is no longer class loaded, which is why the static code block executes only once.

Next, separate the parent class from the creation of the parent class object and observe the test results

 Public class initobjecttest{    publicstaticvoid  main (string[] args) {          Try{            //class.forname ("Parent");            Class.forName ("Parent");         Catch (Exception e) {                    }        System.out.println ("=============== now, we create a Object below ===========" c21>);         New Parent ();}    }

Test results:

The test results conform to the above rules, we first show that the parent class is loaded, so the class is not loaded after the new parent (). When you create an object, you initialize the normal member, then execute the normal code block, and finally call the constructor method.

The following sub-classes are added to test.

 public  class   initobjecttest{ public  static  void   main (string[] args) { try  { // class.forname (" Parent ");         // class.forname ("Parent");  }catch   (Exception e) {} SYSTEM.O        Ut.println ( "=============== now, we create an Object below ==========="  new   child (); }}

Test results:

When we do not show the load class, the new object automatically loads the class. The first four lines of output are the response of the load class. The next six lines are the reaction of creating an object, starting with the normal members of the parent class, then executing the normal code block of the parent class, then calling the parent class construction method, and then performing a similar operation on the subclass. Fully conforms to the creation process described above.

The following test loads the parent class and then creates the subclass object directly.

 Public class initobjecttest{    publicstaticvoid  main (string[] args) {          Try{            //class.forname ("Parent");            Class.forName ("Parent");         Catch (Exception e) {                    }        System.out.println ("=============== now, we create a Object below ===========" c21>);         New Child ();    }}

Test results:

The parent class is loaded first, the child class needs to be loaded when the subclass object is created, the parent class needs to be loaded when the child class is loaded, and the parent class has been loaded before, so there is no reload.

Iii. Summary

Here, the execution timings between static members, static blocks of code, ordinary members, ordinary blocks of code, construction methods, and the modules of the parent class are finished. Divided into load and create two steps to see, very clear, each step involves the loading of the parent class, this is a recursive process. The initialization of a member is preceded by the execution of the code block, because the code block may manipulate the member. Code blocks are often used to initialize members.

  This article personal writing, the level is limited, if there are errors, please point out, welcome to discuss sharing

Initialization process for Java objects (static members, static code blocks, common code blocks, construction methods)

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.