The order in which members are initialized in the Java class

Source: Internet
Author: User
Tags export class

It is important to understand the initialization order of each member of the class in Java so that you can have a global understanding of the class. Don't say too much, just look at the following example
Class father{   static{          System. OUT.PRINTLN ("Parent class static code block initialization");   {          System. OUT.PRINTLN ("Parent code block Initialization");   }   private static String S=print ();   public static String print ()   {          System. OUT.PRINTLN ("Parent class static Method");          Return "Initialization of the parent class static member variable";   Public Father ()   {          System. OUT.PRINTLN ("Parent-class parameterless constructor initialization complete");          Show ();   }   public void Show ()   {          System. OUT.PRINTLN ("Parent class Show () method");}   } Class Son extends father{   static{          System. OUT.PRINTLN ("Subclass Static code block initialization");   }   {          System. Out.println ("Subclass code block Initialization");   }   private static  int i=1;   Private String s= "sub-class privately-owned member variable";   public void Show ()   {          System. Out.println ("Subclass Show () method: I=" +i);   }   Public Son ()   {          System. Out.println ("Subclass constructor Initialization Complete");          Show ();   }} public class Testclassloadseq {public        static void Main (string[] args)       {               new Son ();}       }

  

Output Result:Static code block initialization of the parent classParent class static methodsSubclass Static code block initializationParent Class code block initializationparent class without argument constructor initialization completeSubclass Show () method: I=1Subclass code block initializationSubclass Constructor Initialization completeSubclass member Variable initialization complete: s= Subclass Private Member VariableSubclass Show () method: I=1  from the results you can see that the order in which members of the class is initialized is:1. If an inheritance relationship exists in a class (like son inheriting Father), the base class (Father) of the derived class (son) is initialized first, and then the export class2. The base class first initializes static static blocks > static variables and initializes only once (because static stuff is loaded with the load of the class)3. Then the static initialization of the derived class is the same as the static init of the base class (IBID.)4. Initializing the base class parameterless constructor (invoking a parameter to initialize the parameterized constructor)5. Initialize the exported class parameterless constructor ( Note: the member variables and code blocks of the exported class are earlier than the constructor initialization.) See output results)  in the above output you may see that the show () method is called in the constructor in the base class, so the output may not be surprising, I'll change it now.
1 classFather2 {3           Private StaticString s=print ();4  5    Static{6System. Out.println ("Parent class static code block initialization" );7    }8    {9System. Out.println ("Parent class code block initialization" );Ten    } One     Public StaticString print () A    { -System. Out.println ("Parent class static Method" ); -           return"Initialization of a static member variable of a parent class" ; the    } -     PublicFather () -    { -System. Out.println ("Parent class without parameter constructor initialization complete" ); + Show (); -    } +     Public voidShow () A    { atSystem. Out.println ("Parent class Show () method") ); -    } - } - classSonextendsFather - { -    Static{ inSystem. Out.println ("Subclass Static code block initialization" ); -    } to    { +System. Out.println ("Subclass code block Initialization" ); -    } the    Private intI =1; *    PrivateString s= "sub-class Private member variable" ; $     Public voidShow ()Panax Notoginseng    { -System. Out.println ("Subclass Show () method: i=" +i); the    } +     PublicSon () A    { theSystem. Out.println ("Subclass constructor Initialization Complete" ); +System. OUT.PRINTLN ("Child class member variable initialization completed: s=" +s); - Show (); $    } $ } -  Public classTestclassloadseq { -          Public Static voidMain (string[] args) the        { -                NewSon ();Wuyi        } the   - } Wu   

Output Result:Subclass Static code block initializationParent Class code block initializationparent class without argument constructor initialization completeSubclass Show () method: I=0Subclass code block initializationSubclass Constructor Initialization completeSubclass member Variable initialization complete: s= Subclass Private Member VariableSubclass Show () method: I=1  It can be seen that there is no difference from the above code, the only difference is that I have the static member variable I in the derived class into the member variable I, you can see the result is very different, the result is: 0 cause: Because the static member variable above is initialized with the load of the class, the result is 1 and the following is the member variable because it is still in the base class constructor, so the member variable in the exported class is not initialized so it is 0. so the above initialization order is not complete enough, now the completion of the full:The first time the JVM loads a class, it initializes the default to 0 for each object, and defaults to NULL for reference types that are combined   Summary:in Java, first initialize the base class when initializing the export class (how many base classes are initialized)If there is a mistake I hope that everyone to help put forward the study together (oneself also in the study .... )。Tip: The order in which members are initialized in Java is very important and good mastery is very helpful for future learning.

The order in which members are initialized in the Java class

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.