The initialization order of the properties in the class, constructors, and initialization blocks

Source: Internet
Author: User
For static variables, static initialization blocks, variables, initialization blocks, constructors, their initialization order is (static variable, static initialization block) > (variable, initialization block) > constructor. We can verify this by using the following test code:

Java code
public class Initialordertest {       
      
    //static variable public       
    static String Staticfield = "static variable";       
    Variable public       
    String field = "Variable";       
      
    Static initialization block static       
    {       
        System.out.println (Staticfield);       
        SYSTEM.OUT.PRINTLN ("Static initialization Block");       
    }       
      
    Initialize block       
    {       
        System.out.println (field);       
        System.out.println ("initialization block");       
    }       
      
    Constructor public       
    Initialordertest () {       
        System.out.println ("constructor");       
    }       
      
    public static void Main (string[] args) {       
        new initialordertest ();       
    }       
}   

Running the above code, we will get the following output:
static variables
Static initialization block
Variable
Initializing blocks
Construction device

This is in full conformity with what has been said above. So what happens to the succession situation? We still use a piece of test code to get the final result:


Java code

Class Parent {//static variable public static String P_staticfield = "Parent class-static variable";       
      
    Variable public String P_field = "Parent class-variable";       
        Static initialization block static {System.out.println (P_staticfield);       
    System.out.println ("Parent class-static initialization block");       
        }//Initialization block {System.out.println (P_field);       
    System.out.println ("Parent class-Initialization block");       
    }//Constructor public parent () {SYSTEM.OUT.PRINTLN ("parent class-constructor"); The public class subclass extends Parent {//static variable public static String S_stati       
    Cfield = "Subclass--static variable";       
    Variable public String S_field = "Subclass--variable";       
        Static initialization block 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");       
    }//Builder public subclass () {System.out.println ("subclass--constructor");       
    }//Program entry public static void main (string[] args) {new subclass ();     }       
}

Run the above code, the results immediately appear in front of our eyes:
Parent class--Static variables
Parent class--static initialization block
Subclasses--Static variables
Subclass--Static initialization block
Parent class--variable
Parent class--Initialize block
Parent class--builder
Subclasses--variables
Subclass--Initialize block
Subclass--Builder

Now, the results have been self-evident. You may notice that the initialization of subclasses is not done until the parent class is fully initialized, and that the initialization of static and static initialization blocks of subclasses is done before the variables, initialization blocks, and constructors of the parent class are initialized.

So what is the sequence between a static variable and a static initialization block, a variable, and an initialization block? Whether a static variable is always preceded by a static initialization block, the variable is always initialized before the initialization block. It actually depends on the order in which they appear in the class. We use static variables and static initialization blocks as examples to illustrate.

Again, we're going to write a class to test:


Java code
Class Testa {
    Public Testa () {
        System.out.println ("test--a");
    }

Class Testb {public
    testb () {
        System.out.println ("Test--b");
    }

public class Testorder {

    //static variable public
    static Testa a = new Testa ();

    Static initialization block static
    {
        System.out.println ("Static initialization Block");
    }

    Static variable public
    static TESTB B = new Testb ();

    public static void Main (string[] args) {
        new Testorder ();
    }
}


Running the above code, you will get the following result: test--a static initialization block Test--b you can arbitrarily change the variable A, variable B and the static initialization block before and after the position, you will find that the output as they appear in the class before and after the sequence changes, This means that static variables and static initialization blocks are initialized according to the order in which they are defined in the class. Similarly, variables and initialization blocks follow this rule.

After understanding the initialization order of classes under inheritance, how to determine the final output is solved

Summarize:

1, the syntax format of the constructor

Modifiers: public Private,protected,default

Class Name: constructor must have the same name as the class name

Argument list 2, constructor's return value type

The constructor cannot define the type of the return value. If the type of the return value is defined, the compilation does not complain because the JVM has used the so-called constructor as a common method. No return value type is not without a return value, the constructor has a return value, and the object of the current class is returned. Therefore, the return value type of the constructor is always the current class, so there is no type that defines the return value. It can be understood that the return value of the constructor is implicit. 3 default builder,

If the program does not display a definition constructor, the system defaults to the program with a parameterless constructor. Once the constructor is added, the default constructor does not exist. 4, the constructor is an important way to create an object, does it mean that the constructor is entirely responsible for creating objects?

No, the constructor is an important way to create an object, and the isomorphism new keyword calls the constructor or returns an instance of the class, but the process is not fully executed by the constructor.

In fact, when the system calls the constructor, the system allocates the memory space for the object, assigns an initial value to the object's member variable, and this time the object has been created---these actions are performed before the constructor's execution body. That is, the object already exists before execution of the constructor. Just can't be called by an external program, the object can be invoked by an external program after the constructor is executed. 5, overload of the constructor

Public class Constructordemo {

Private int A;

Private String s;

Public Constructordemo () {

}

Public Constructordemo (int a) {

this. A = A;

}

Public Constructordemo (String s,int a) {

This (a);

this. s = s;

}

} 6, initialization block (code block)

Initialization blocks can be treated as a member of a Java program, code block is divided into: Static code block and Non-static code block, a class can have more than one code block, the order of code block execution is based on the location of the code block in the program to determine. Static code blocks are always executed more than non-static blocks of code

Non-static code block: It can be understood as a member property of a class. Every time you create an object, it's a member variable.

Static code block: The same can be understood as a class variable, only when the class is loaded to execute.

The order in which the program initializes the properties is: the code block à attribute declaration specifies the initial value of the value 7 specified in the constructor , initialization blocks and constructors

To some extent, it can be understood that initialization is a complement to the constructor, because initialization is always performed before the constructor, and the object can also be initialized.

Unlike constructors, the initialization block can only perform a fixed piece of code, cannot accept parameters like constructors, and initializes all objects of the class.

As with constructors, a program executes not only the initialization of the current class, but also the constructor, goes back to the initialization fast and constructor of the object class. Executes the initialization block and constructor of the parent class (first initialize the block, then the constructor), and then executes the initialization block and constructor for the current 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.