Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to the initialization order of Java classes and objects

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "introduction to the initialization order of Java classes and objects". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Class loading step

In Java, the class loader loads a class into the Java virtual machine through three steps: loading, linking and initialization, in which the link can be divided into three steps: verification, preparation and parsing. In addition to parsing, the other steps are completed in strict order. The main work of each step is as follows:

Loading: finding and importing binary data for a class or interface

Link: perform the following verification, preparation, and parsing steps, where the parsing steps are optional

Check: check the correctness of the binary data of the imported class or interface

Prepare: allocate and initialize storage space to static variables of the class

Parsing: converting symbolic references to direct references

Initialization: initializes the Java code and static Java code blocks for the static variables of the active class.

Initialization consists of two parts:

1. Class initialization (initialization class & interface)

two。 Creation of the object (creation of new class instances).

Because class initialization is actually a step of class loading (loading of classes), many books attribute it to the step of "object creation". In fact, it's just a different point of view. In order to understand more clearly, it is still separated here.

Order:

Because the loading of the class must be a * step, the initialization of the class comes first. The general initialization order is:

Class initialization-> subclass constructor-> parent constructor-> instantiate member variables-> continue executing statements of subclass constructor

Let's explain it in detail with an example.

1. Initialization of the class (Initialization classes and interfaces)

In fact, it is very simple, specifically, there are:

(a) initialization class (initialization of class), which refers to initializing static field and executing static initialization blocks.

Public class Demo {/ / initialize static field, / / where = "initialization static field" is also called static field initializer private static String str = "initialization static field"; / / initialization block, also known as static initializer, or static initialization block static {System.out.println ("This is static initializer");}}

Btw, the concepts of static initializer and static field initializer are mentioned in some books, as well as instance initializer and instance variable initializer. The comments in the example have already explained its meaning.

(B) initialization interface (initialization of interface), which refers to initializing the field defined in the interface.

* Note *

1. When initialization classes, the superclass of the class will be initialized first, but the interface that it implements will not.

When initialization classes, the superclass of the class and the superclass of the superlcass are first initialized recursively until java.lang.Object. When initialiazation interface, however, this is not necessary, only the interface itself is initialized.

two。 For initialization raised by a reference class variable (class field), only the class that actually defines the field is initialized.

3. If a static field is a compile-time constant (compile-time constant), a reference to it does not cause initialization of the class that defines it.

To help understand the two points, try the following example:

Initialization class

Public class Initialization {static {System.out.println ("Initialization Main class");} public static void main (String [] args) {System.out.println (Sub.y); System.out.println (Sub.x); System.out.println (Sub.z);}}

Sub class

Public class Sub extends Super {public static final int y = 2005; public static int z; static {System.out.println ("Initialization Sub");}}

Super class

Public class Super {public static int x = 2006; static {System.out.println ("Initialization Super");}}

Enter the result

Initialization Main class 2005 Initialization Super 2006 Initialization Sub 0

From this result, we can see

The static block is executed first in the class; (actually the static member variables are loaded first, followed by the static code block)

The final variable of static does not cause class initialization

If the subclass Sub refers to the variable in the parent class Super, it will cause the initialization of the parent class, but not the initialization of the subclass.

Member variables of static also have default values.

two。 Creation of objects (creation of new class instances)

Look at the examples to illustrate:

InitializationOrder class

Public class InitializationOrder {public static void main (String [] args) {SubClass sb = new SubClass ();}}

SuperClass class

Public class SuperClass {static {System.out.println ("SuperClass static");} SuperClass (String str) {System.out.println (str);}}

Interface class

Interface Interface {static SuperClass su = new SuperClass ("Interface new SuperClass");}

SubClass class

Public class SubClass extends SuperClass implements Interface {static {System.out.println ("SubClass static");} private SuperClass su = new SuperClass ("initialization variable"); SubClass () {super ("super"); new SuperClass ("new SuperClass");}}

Output result

SuperClass static SubClass static super initialization variable new SuperClass

Explain:

1) the Java virtual machine executes the static method main () in the InitializationOrder class, which causes the class to initialize. Start initializing the InitializationOrder class. Skip the specific steps.

2) after the InitializationOrder class is initialized, the main () method is executed. The statement SubClass sb = new SubClass () creates a SubClass object. Class SubClass is initialized after loading, because Subclass has a parent class, SuperClass, so initialize the SuperClass class first. So you see the output "SuperClass static".

3) after the SuperClass class is initialized, initialize the SubClass class and output "SubClass static".

4) at this point, the loading of the class is complete. Begin the process of creating an object for SubClass. First allocate memory space for the SubClass class and its parent class SuperClass class, and then Super su is assigned to null.

5) execute the constructor SubClass (), execute super (), call the constructor of the parent class, and output "super".

6) initialize the member variable su of the SubClass class and output "initialization variable".

7) continue to execute the rest of the constructor, execute new SuperClass ("new SuperClass"), output "new SuperClass", and Super su is assigned a reference to the new object.

8) although SubClass implements the interface Interface, initializing it does not cause the interface to initialize, so the static SuperClass su = new SuperClass ("Interface new SuperClass") in the interface Interface has not been executed from beginning to end.

Therefore, the specific steps for creating an object are as follows:

(1) all member variables-including the class and the member variables in its parent class-are allocated memory space and assigned default values. (here is the * initialization of member variables)

(2) initialize its parameter variables for the called constructor. (if there are parameters)

(3) if other constructors of the same class are called with this in the constructor, follow step (2) ~ (6) to process the called constructor.

(4) if the constructor of its parent class is called with super in the constructor, the called parent constructor is processed according to step (2) ~ (6).

(5) execute instance initializer and instance variable initializer to initialize member variables in writing order. (this is the second time to initialize member variables)

(6) execute the rest of the constructor in writing order.

*******************

Summary:

From the initialization of the class and the creation of the object, we can know that a class initializes the variables of static and the static sentence block first, then allocates the memory space of the member variables of the class and the parent class, assigns default values, and then starts to call the constructor. Between the subclass and the parent class, initialize and create the parent class first, and then initialize and create the subclass.

This is the end of the introduction to the initialization order of Java classes and objects. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report