Loading order of classes and objects in Java

Source: Internet
Author: User

first, let's look at the fundamentals of Java Virtual machine initialization.

The JVM makes the type available to a running Java program by adding, connecting, and initializing a Java type. The life cycle of the type is as follows:


The mount and connection must be completed before initialization.


Class initialization phase, primarily assigning the correct initial value to the class variable. The "correct" initial value here refers to the starting value that the programmer expects the class variable to have. A correct initial value is given by a class variable initialization statement or static initialization statement. Initializing a class consists of two steps:


1) If the class has a direct superclass, and the direct superclass is not initialized, the direct superclass is initialized first.


2) Executes this method if the class has a class initialization method.


When will the class be initialized? The Java virtual machine specification is strictly defined for the initialization time of a class: initialized on first active use.


What are the conditions that meet the first-time active use criteria? The Java Virtual Machine specification explains this, respectively:


1) Create a new instance of the class;


2) Call the static method of the class;


3) The static field of the Operation class or interface (except the final field);


4) Invoking the specific reflection method of Java;


5) Initializes a subclass of a class;


6) Specify a class as the initialization class when the Java virtual machine starts.


In addition to the above six scenarios, all other methods are passive and do not cause initialization of the class.


Once a class is loaded, connected, and initialized, it is ready to be used. Now let's focus on the instantiation of objects, object instantiation and initialization is the activity of the beginning of the object's life.


The Java compiler generates at least one instance initialization method, the <init> () method, for each class it compiles. Each class in the source code is constructed with a corresponding <init> () method. If the class does not explicitly declare any constructor methods, the compiler generates a default parameterless constructor for the class, which simply calls the parent class's parameterless constructor.


A <init> () method may contain three of the code content: calling another <init> () method, initializing the instance variable, and constructing the code for the method body.
If the constructor is explicitly started by calling another constructor in the same class, its corresponding <init> () method body includes the following:


A call to the <init> () method of this class;
The byte code of the method body of the corresponding construction method is implemented.
If the constructor is not started by calling other constructors of its own class, and the object is not an object, the <init> () method includes the following:

A call to the <init> () method of a parent class;
The byte code of the initialization method of any instance variable;
The byte code of the method body of the corresponding construction method is implemented.

Well, let's look at the code in the form of a specific analysis:

Superinitfield p = new Superinitfield ();  The Superinitfield superclass is Object  //Create Superinitfield object, which belongs to the first active use, so first initialize the object class, Then call the Superinitfield class variable initialization statement or static initialization statement, so to output the static parent  //class is loaded, connected and initialized after the creation of an object, so you need to first call the object's default construction method, Then call your own constructor, so you want to output the parent    Superinitfield C = new Subinitfield ();  Subinitfield inherits from Superinitfield  //Create Subinitfield object, belonging to the first active use, parent class Superinitfield has been initialized, So whenever you call a Subinitfield class variable initialization statement or a static initialization statement, you want to output the static child  

in detail about the static block of code in Java

Static represents the meaning of "global" or "static", which modifies member variables and member methods, and can also form statically static blocks of code, but there is no concept of global variables in the Java language. member variables and member methods that are modified by static are independent of any object of the class. That is, it does not depend on class-specific instances and is shared by all instances of the class.


As long as this class is loaded, the Java virtual machine can find them based on the class name in the method area of the run-time data area. Therefore, a static object can be accessed before any of its objects are created, without referencing any objects. Static member variables and member methods that are decorated with public are essentially global variables and global methods, and when declaring the object city of its class, do not generate a copy of the static variable, but all instances of the class share the same static variable.


The static variable can have a private adornment before it, indicating that the variable can be used in the static code block of the class, or in other static member methods of the class (which can also be used in non-static member methods-nonsense), but it is important that the class name cannot be referenced directly in other classes. In fact, you need to understand that private is the access permission limit, static means do not instantiate can be used, so it is easier to understand more. Static plus other access keyword effects and so on.


The static modified member variables and member methods are customarily referred to as static variables and static methods, which can be accessed directly through the class name, and Access syntax is:
Class name. static method Name (parameter list ...)
Class name. Static variable Name


A static code block is represented by a statically decorated block of code that executes when the Java Virtual Machine (JVM) loads the class (very useful, hehe).


1. Static variables
There are two ways to classify a class member variable statically: A variable that is statically modified, called a static variable or a class variable, and another variable that is not modified by static, called an instance variable.


The difference between the two is:
For static variables there is only one copy in memory (memory saving), the JVM allocates only one memory at a time, completes the memory allocation of static variables during the loading of the class, can be accessed directly (conveniently) by the class name, and, of course, is accessible through objects (but this is not recommended).
For instance variables, when an instance is not created, the instance variable is allocated one memory, and the instance variable can have multiple copies in memory without compromising (flexibility).


As a result, static variables are typically used when you need to implement the following two functions:
 when sharing values between objects
 Easy access to variables




2. Static method
Static methods can be called directly from the class name, and any instance can also be called.
Therefore, the this and Super keywords cannot be used in a static method, and you cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static), only the static member variables and member methods of the owning class.
Because instance members are associated with specific objects! This need to understand, want to understand the truth, not the memory!!!
Because the static method is independent of any instance, the static method must be implemented, not abstract.


For example, to facilitate the invocation of a method, all methods in the math class in the Java API are static, and the static method inside the generic class is convenient for other classes to call the method.


A static method is a special kind of method inside a class that declares the corresponding method static only when it is needed, and a method inside a class is generally non-static


3. Static code block


A static block of code is also called a code block, which is an independent block of static blocks in a class that is separate from a class member, can have more than one position, it is not in any method body, and the JVM executes these static blocks of code when the class is loaded, and if there are multiple static blocks of code, The JVM executes them sequentially in the order in which they appear in the class, and each code block is executed only once. For example:

Operation Result:

3
Hhahhahah
1000
4
5

4. What does static and final piece mean?
Static final is used to modify member variables and member methods, which can be simply understood as "global constants"!
For variables, this means that once a value is given it cannot be modified and is accessible through the class name.
For methods, the representation is not overwritten and can be accessed directly through the class name.


Sometimes you want to define a class member so that its use is completely independent of any object of that class. Typically, a class member must be accessed through the object of its class, but it can create a member that can be used by itself without referencing a particular instance. Such a member can be created by adding the keyword static (static) before the member's declaration. If a member is declared static, it is able to be accessed before any object of its class is created, without having to reference any object. You can declare methods and variables as static. The most common example of a static member is main (). Because main () must be called when the program starts executing, it is declared as static.


A variable declared as static is essentially a global variable. When declaring an object, the copy of the static variable is not produced, but all instance variables of the class share the same static variable. The method declared as static has the following limitations:
? They can only invoke other static methods.
? They can only access static data.
? They cannot refer to this or super in any way (the keyword super is related to inheritance, as described in the next chapter).
If you need to initialize your static variable with a calculation, you can declare a static block that executes only once when the class is loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

Class Usestatic {static int a = 3;static int b;static void meth (int x) {System.out.println ("x =" + x); System.out.println ("a =" + a); System.out.println ("b =" + b);} static {System.out.println ("static block initialized."); b = A * 4;} public static void Main (String args[]) {meth (42);}}
Once the Usestatic class is loaded, all static statements are run. First, A is set to 3, then the static block executes (prints a message), and finally, B is initialized to a*4 or 12. Then call Main (), main () call meth () and pass the value 42 to X. The 3 println () statements refer to two static variables A and B, and the local variable x.
Note: Referencing any instance variable in a static method is illegal.

The following is the output of the program:

Static block initialized.
x = 42
A = 3
b = 12
Outside of the classes that define them, static methods and variables can be used independently of any object. This way, you can just add the number operator to the name of the class. For example, if you want to invoke a static method from outside the class, you can use the following common format:
Classname.method ()
Here, ClassName is the name of the class, and the static method is defined in the class. As you can see, this format is similar to calling a non-static method through an object reference variable. A static variable can be accessed in the same format-the class name dot number operator. This is how Java implements a control version of global functionality and global variables.

Java static code block static method differences
In general, if some code must be executed at the time of project startup, the use of static code blocks, the code is active, it needs to be initialized when the project is started, in the case of not creating the object, other programs to invoke, the need to use a static method, the code is passive execution. Static methods are loaded when the class is loaded and can be called directly with the class name
For example, the main method must be static, which is the program entry.
The difference between the two is: static code blocks are automatically executed;
Static methods are executed only when they are called.


Static methods
(1) In Java, you can define a method that does not need to create an object, which is a static method. To achieve this effect, you only need to add the static keyword before the method defined in the class. For example:


public static int maximum (int n1,int n2)


When using static methods of a class, note that:


A static method can only invoke other static members (including variables and methods) directly in the same class, and cannot directly access non-static members in the classes. This is because, for non-static methods and variables, you need to create an instance object of the class before you can use it, and the static method does not have to create any objects before it is used.


b Static methods cannot reference the this and Super keywords in any way, because static methods do not have to create any instance objects before they are used, and when a static method is called, the object referenced by this is not produced at all.


(2) A static variable is a variable that belongs to the entire class and not to an object. Note that variables in any method body cannot be declared static, for example:
Fun ()
{
static int i=0;//illegal.
}


(3) A class can use a static block of code that is not contained in any method body, when the class is loaded, a static code block is executed, and only once, static blocks are used to perform initialization of class properties. For example:
Static
{
}

Initialization order of static code blocks


Class parent{
static String name = "Hello";
{
System.out.println ("parent block");
}
static {
SYSTEM.OUT.PRINTLN ("Parent static block");
}
Public Parent () {
System.out.println ("parent constructor");
}
}


Class Child extends parent{
static String ChildName = "Hello";
{
System.out.println ("Child Block");
}
static {
SYSTEM.OUT.PRINTLN ("Child static Block");
}
Public Child () {
System.out.println ("Child constructor");
}
}


public class Staticiniblockordertest {


public static void Main (string[] args) {
New Child ();//Statement (*)
}
}
 


Parent static Block
Child static Block
Parent Block
Parent constructor
Child block
Child constructor
  


Analysis: When the new Child () is executed, it first goes to see if there is a static block of code inside the parent class, and if so, it first executes the contents of the static code block inside the parent class, and then executes the static block of code inside the subclass (own class) after the contents of the static code block inside the parent class are executed. When the static code block of a subclass executes, it goes on to see if the parent class has no non-static block of code, and if there is a non-static block of code that executes the parent class, the non-static code block of the parent class is executed, and the parent class's constructor is executed, and then it goes to see if the subclass has non-static A non-static block of code that executes subclasses if there is one. The non-static code block of the subclass executes and then executes the subclass's constructor, which is the initialization order of an object.


Summarize:
Object Initialization order: first executes the parent class static content, after the parent class static content executes, then executes the subclass static content, when the subclass static content executes completes, then goes to see the parent class has not the non-static code block, if has executes the non-static code block of the parent class, the parent class's non-static code block executes, The constructor of the parent class is then executed, and after the construction method of the parent class is executed, it goes on to see if the subclass has no non-static block of code, and if there is a non-static block of code that executes the subclass. The non-static code block of the subclass executes and then executes the subclass's construction method. In short, the static code block content executes first, then executes the parent class non-static code block and construction method, then executes the subclass non-static code block and constructs the method.


Note: The constructor of a subclass, regardless of the constructor with no arguments, will first look for the parent class's constructor without parameters. If the parent class does not have a constructor with no arguments, the subclass must use the supper key to call the parent class with the constructor of the parameter, otherwise the compilation cannot pass.


Loading order of classes and objects in Java

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.