Java class initialization

Source: Internet
Author: User

Java class initialization

Java provides two different initialization types: class initialization and object initialization. The class members are static and a value is set by default. Object initialization is performed in the constructor. However, if you want to assign a static variable non-default value or initialize a class of Common Object Attributes (no matter which constructor is called), you need some special methods. Static initialization blocks and non-static initialization blocks are provided to handle these two situations.

Static initialization blocks are defined through static. A simple code example is as follows:

public class CorderStatic {staticint idx;static{    System.out.println("idx: " + Integer.toString(idx++));    System.out.println("idx: " + Integer.toString(idx));}publicstatic void main(String[] argv) {    System.out.println("DONE");}}
The result of code execution is:

Idx: 0

Idx: 1

DONE

The output result shows that the static initialization block is called after the static member is initialized. In addition, if the class contains multiple static initialization blocks, it is called according to the order in which the block appears.

  1. Non-static initialization Block

Non-static initialization blocks are defined in {} blocks. The difference between static initialization block and static initialization block is that there is no static keyword rhetoric. The test code is as follows:

public class CorderInstance {    int idx;{    System.out.println("idx: " + Integer.toString(idx++));    System.out.println("idx: " + Integer.toString(idx++));}publicCorderInstance() {    System.out.println("idxin constructor : " + Integer.toString(idx));}public static void main(String[] argv) {    newCorderInstance();    System.out.println("DONE");}}

The code output is as follows:

Idx: 0

Idx: 1

Idxin constructor: 2

DONE

It can be seen that non-static initialization blocks are called before object attribute initialization ends and constructor calls.

  1. Initialization order

If a class defines static and non-static initialization blocks, which one will be executed first? The test code is as follows:

public class Corder {static int staticpro;static{    System.out.println("staticblock : " + Integer.toString(staticpro));}int instancepro;{    System.out.println("non-staticblock." + Integer.toString(instancepro++));}publicCorder() {    System.out.println("instanceproperty : " + Integer.toString(instancepro++));    System.out.println("Theconstructor had been complete.");}publicstatic void main(String[] argv) {    newCorder();}}


The code output is as follows:

Staticblock: 0

Non-staticblock.0

Instanceproperty: 1

Theconstructor had been complete.

It can be seen that the static initialization block will be called first, then the non-static initialization block, and finally the constructor.

  1. Inheritance and initialization

Initialization blocks become more complex when class inheritance occurs. First, paste the test code:

public class CorderInherit {static int staticpro;staticA a;static{    System.out.println("staticinitialization : " + Integer.toString(staticpro));    if(a == null) {        System.out.println("classa is null.");    }    a= new B(10);}intinstancepro;A aa;{    instancepro= 10;    System.out.println("specialblock." + Integer.toString(instancepro));    aa= new B(10);}publicCorderInherit(int i) {    System.out.println("instanceproperty : " + Integer.toString(instancepro));    instancepro= i;    System.out.println("staticproperty : " + Integer.toString(staticpro));    System.out.println("instanceproperty : " + Integer.toString(instancepro));    System.out.println("Theconstructor had been complete.");}    publicstatic void main(String[] argv) {        newCorderInherit(-1);    }}class A {    static int index;    static{        System.out.println("ClassA static 1 " + Integer.toString(index++));    }    {        System.out.println("ClassA special 1 " + Integer.toString(index++));    }    public A() {        System.out.println("constructclass A." + Integer.toString(index++));    }    static{        System.out.println("classA static 2 " + Integer.toString(index++));    }    {        System.out.println("ClassA Special 2 " + Integer.toString(index++));    }}class B extends A {     static int index;     static{         System.out.println("ClassB static 1 " + Integer.toString(index++));     }     {         System.out.println("ClassB special 1 " + Integer.toString(index++));     }     public B(int i) {         System.out.println("constructclass B." + Integer.toString(index++));     }     static{         System.out.println("classB static 2 " + Integer.toString(index++));     }     {         System.out.println("ClassB Special 2 " + Integer.toString(index++));      }}


The code output is as follows:

Staticinitialization: 0

Classa is null.

ClassA static 1 0

ClassA static 2 1

ClassB static 1 0

ClassB static 2 1

ClassA special 1 2

ClassA Special 2 3

Constructclass A.4

ClassB special 1 2

ClassB Special 2 3

Constructclass B .4

Specialblock.10

ClassA special 1 5

ClassA Special 2 6

Constructclass A.7

ClassB special 1 5

ClassB Special 2 6

Constructclass B .7

Instanceproperty: 10

Staticproperty: 0

Instanceproperty:-1

Theconstructor had been complete.

Observe the above output. We can see that when B's object is instantiated, the virtual opportunity is to load B. class, but because B inherits A, A. class will also be loaded. This causes the static initialization blocks of A and B to be called separately. When constructing objects of B, non-static initialization blocks and Default constructors of A are called, and then non-static initialization blocks and constructors of B are called.

  1. Conclusion

The above example shows that the complete initialization sequence of the class is as follows (the subclass is the current class, or the class to be new ):


When is Java class initialized?

We know that a class must be loaded, connected, and initialized to be used. The following is a brief description of the three stages, and then a simple example will be used to illustrate the class initialization process in java.

During the loading phase, the class Loader (Bootstrap ClassLoader or custom ClassLoader) loads the compiled Class file into the memory and creates class objects related to the Class, this Class Object encapsulates the type information of the Class we want to use.

The connection phase can be divided into three sub-steps: verification, preparation, and resolution.
Verify that the java data format is correct and applicable to JVM.
During preparation, JVM allocates memory space for static variables and sets the default value. Note that the default value is set here. For example, int type variables are assigned the default value 0. At this stage, the JVM may allocate memory for some data structures to improve the performance of the running program, such as the method table.
The parsing process is to find the symbolic references of classes, interfaces, fields, and methods in the constant pool of the type, and replace these symbolic references with direct references. This stage can be postponed until initialization. When a symbol is referenced during the program running, it will be parsed.

Class will perform initialization when it is "active" for the first time, and assign the correct initial value to the class (static) variable. In Java code, a correct initial value is given through the class variable initialization statement or static initialization block. The active usage here includes:
1. Create a class instance
2. Call static methods of the class
3. Use non-constant static fields of the class
4. Call some reflection methods in Java APIs
5. initialize a subclass of A Class
6. When the class containing the main () method is started

Initializing a class involves two steps:
1. If the class has a direct parent class and the direct parent class has not been initialized, initialize its direct parent class first.
2. If the class has an initialization method, execute this method.
Note: The initialization interface does not need to initialize its parent interface.

JAVA initialization and class loading

It is unlikely that you fully use code to prove the actions of class loading, because before you use this class (that is, when you want to start to prove the process of class loading), she has loaded.

For now, static members are initialized together with the class loading, so a maximum of static members can be used to prove the class loading.

The problem is how to prompt messages when static members are initialized. There are two methods:

The first is to use static field members. This member is designated as an object initialization and will be notified in the constructor of this initialization object. Code:
Public class StaticLoad {
Public static loadpolicy = new loadpolicy ();
}

Public class loadpolicy {
Public loadpolicy (){
System. out. println ("Class is Loaded ");
}
}
When the StaticLoad Class is used, static members are initialized when the Class is Loaded to prove that the Class is Loaded, and only one call is made once.

The second method is to use static blocks. The Code is as follows:
Public class StaticLoad {
Public static loadpolicy = new loadpolicy ();
Static {
System. out. println ("Class is Loaded ");
}
}
When the class is loaded, the code in the static block is also executed.

This is the method for notification when the class is loaded. You can write the code yourself and they will only play it once.

For the loading sequence of classes, there are detailed information on the Internet. Here I will only talk about some simple:
First, you need to use a class to read such code from classpath to the code storage area of the memory class, and then open a storage area for each static field, then store the method code. Next, initialize the class. All static members are initialized in sequence (from top to bottom in the Code Declaration Order). When other classes need to be loaded, load other classes. Then complete the initialization for the virtual machine.
When instantiating a class, if it needs to be loaded, it will be loaded in the above order, and then allocate the space of all instance fields in the memory, and then call the constructor, the constructor calls the parent Constructor (displayed or implicitly) and executes the remaining constructor code. Finally, return the reference of the instantiated object and return the constructor.

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.