Usage of static code blocks in Java

Source: Internet
Author: User

Static indicates the meaning of "global" or "static". It is used to modify member variables and member methods. It can also form static code blocks, but Java does not have the concept of global variables. The static modified member variables and member methods are independent of any object in the class. That is to say, it is shared by all instances of the class and does not depend on a specific instance of the class.

As long as the class is loaded, the Java Virtual Machine can locate the class names in the Method Area of the runtime data zone. Therefore, a static object can be accessed before any of its objects are created without referencing any objects. Static member variables and member Methods Modified with public are essentially global variables and global methods. When the object city of the declared class does not generate a copy of static variables, instead, all instances of the class share the same static variable.

The static variable can be modified in private, indicating that the variable can be in the static code block of the class, or other static member methods of the class (you can also use -- nonsense in non-static member methods), but it cannot be directly referenced by the class name in other classes, this is important. In fact, you need to understand that private is the access permission limitation, and static means that it can be used without instantiation, so that it is much easier to understand. The effect of adding other access key words before static is also similar.

Static modified member variables and member methods are usually called static variables and static methods. They can be accessed directly by class names. The access syntax is as follows:
Class Name. Static Method Name (parameter list ...)
Class Name. static variable name

A static code block is a static code block. When a Java Virtual Machine (JVM) loads a class, the code block is executed (very useful ).

  1. Static variables
Class member variables can be classified by static or not. One is static modified variables, such as static variables or class variables; the other is a variable that is not modified by static, called an instance variable.

The difference between the two is:
For static variables that only have one copy (memory saving) in the memory, JVM only allocates the memory for the static one time, and completes the memory allocation of the static variables during the loading process, you can directly access the available class name (convenient). Of course, you can also access it through an object (but this is not recommended ).
If an instance variable is not created, the instance variable will be allocated with memory once. The instance variables can be copied multiple times in the memory without affecting each other (flexible ).

Therefore, static variables are generally used to implement the following functions:
When sharing values between objects
Convenient variable access

  2. Static Method
Static methods can be called directly by class names, and can be called by any instance,
Therefore, the keyword "this" and "super" cannot be used in static methods, and the instance variables and instance methods of the class cannot be directly accessed (that is, the static member variables and Member member methods are not included ), only static member variables and member methods of the class can be accessed.
Because instance members are associated with specific objects! You need to understand the truth, not the memory !!!
Because the static method is independent of any instance, the static method must be implemented rather than abstract.

For example, to facilitate method calling, all the methods in the math class in Java API are static, while the static method in the general class is also convenient for other classes to call this method.

Static methods are a special class of internal methods. They are declared as static only when needed. Internal methods of a class are generally non-static.

  3. Static code block

A static code block is also called a static code block. It is a static statement Block Independent of class members in a class. It can have multiple static code blocks and can be placed anywhere. It is not in any method body, when a JVM loads a class, it executes these static code blocks. If there are multiple static code blocks, the JVM executes them in sequence according to the sequence they appear in the class, and each code block is executed only once. For example:

Public class test5 {Private Static int A; private int B; static {test5.a = 3; system. out. println (a); test5 T = new test5 (); T. F (); T. B = 1000; system. out. println (T. b);} static {test5.a = 4; system. out. println (a);} public static void main (string [] ARGs) {// todo Automatic Generation Method stub} static {test5.a = 5; system. out. println (a);} public void F () {system. out. println ("hhahhahah ");}}

Running result:

3hhahhahah100045

Static code blocks can be used to assign values to some static variables. In the end, these examples all use a static main method, so that the JVM can directly call the main method without creating an instance.

  4. What does static and final use to represent?
Static final is used to modify member variables and member methods. It can be simply understood as a "global constant "!
For a variable, it means that once the value is given, it cannot be modified and can be accessed through the class name.
For methods, it means they cannot be overwritten and can be accessed directly by class names.

Sometimes you want to define a class member so that its use is completely independent of any object of the class. Generally, a class member must be accessed through its class object, but can create such a member, which can be used by itself without referencing a specific instance. Add the keyword static before the declaration of the member to create such a member. If a member is declared as static, it can be accessed before any object of its class is created without referencing any object. You can declare both methods and variables as static. The most common example of static members is main (). Because the main () must be called when the program starts execution, it is declared as static.

Variables declared as static are actually global variables. When declaring an object, it does not produce a copy of the static variable, but all instance variables of this class share the same static variable. Methods declared as static have the following restrictions:
• They can only call other static methods.
• They can only access static data.
• They cannot reference 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 through calculation, you can declare a static block, which is only executed once when the class is loaded. The following example shows that the class has a static method, some static variables, and a static initialization block:

// Demonstrate static variables,methods,and blocks.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 is executed (print a message), and finally, B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to X. The three println () Statements reference two static variables A and B, and the local variable X.

Note: It is invalid to reference any instance variable in a static method.

The output of the program is as follows:

Static block initialized.x = 42a = 3b = 12 

Outside the class that defines them, static methods and variables can be used independently of any object. In this way, you only need to add the number operator after the class name. For example, if you want to call a static method from outside the class, you can use the following common format:

Classname. Method ()

Here, classname is the class name and defines the static method in this class. As you can see, this format is similar to that used to call non-static methods through object reference variables. A static variable can access the -- class name plus vertex operator in the same format. This is a control version of how Java implements global functions and global variables.

The following is an example. In Main (), the static methods callme () and static variables B are accessed outside of their classes.

class StaticDemo {static int a = 42;static int b = 99;static void callme() {System.out.println("a = " + a);}}class StaticByName {public static void main(String args[]) {StaticDemo.callme();System.out.println("b = " + StaticDemo.b);}} 

The output of the program is as follows:

a = 42b = 99

Static members cannot be accessed by instances created by their class. If a member without static modification is an object member, it is owned by each object. The member with static modification is a class member, which can be directly called by a class and is shared by all objects.

1. Static variables
Class member variables can be classified by static or not. One is static modified variables, such as static variables or class variables; the other is a variable that is not modified by static, called an instance variable.

The difference between the two is:
For static variables that only have one copy (memory saving) in the memory, JVM only allocates the memory for the static one time, and completes the memory allocation of the static variables during the loading process, you can directly access the available class name (convenient). Of course, you can also access it through an object (but this is not recommended ).
If an instance variable is not created, the instance variable will be allocated with memory once. The instance variables can be copied multiple times in the memory without affecting each other (flexible ).

Therefore, static variables are generally used to implement the following functions:
When sharing values between objects
Convenient variable access

2. Static Method
Static methods can be called directly by class names, and can be called by any instance,
Therefore, the keyword "this" and "super" cannot be used in static methods, and the instance variables and instance methods of the class cannot be directly accessed (that is, the static member variables and Member member methods are not included ), only static member variables and member methods of the class can be accessed.
Because instance members are associated with specific objects! You need to understand the truth, not the memory !!!
Because the static method is independent of any instance, the static method must be implemented rather than abstract.

For example, to facilitate method calling, all the methods in the math class in Java API are static, while the static method in the general class is also convenient for other classes to call this method.

Static methods are a special class of internal methods. They are declared as static only when needed. Internal methods of a class are generally non-static.

(1) differences between static methods for Java static code blocks
Generally, if some code must be executed when the project is started, a static code block is required. This code is actively executed and needs to be initialized when the project is started, when other programs call an object without creating an object, a static method is required. Such code is passively executed. static methods can be called directly by class name when they are loaded.
For example, the main method must be static. This is the program entry.
The difference between the two is that static code blocks are automatically executed;
Static methods are executed only when they are called.

Static Method
(1) in Java, you can define a method that does not need to create an object. This method 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)

Note the following when using static methods of the class:

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

The static method B cannot reference the this and super keywords in any way, because the static method does not need to create any instance objects before use. When the static method is called, the objects referenced by this are not generated at all.

(2) static variables belong to the entire class instead of an object. Note that the variables in any method body cannot be declared as static. For example:
Fun ()
{
Static int I = 0; // invalid.
}

(3) A class can use a static code block that is not included in any method body. When the class is loaded, the static code block is executed and only executed once, static blocks are often used to initialize class attributes. For example:
Static
{
}

Class loading steps
In Java, the Class Loader loads a class into a Java Virtual Machine. Three steps are required: Loading, linking, and initialization, the link can be divided into three steps: verification, preparation, and resolution. In addition to resolution, the other steps are completed in strict order. The main work of each step is as follows:

Load: Query and import binary data of classes or interfaces;
Link: perform the following verification, preparation, and resolution steps. The resolution steps are optional;
Verify: Check whether the binary data of the import class or interface is correct;
Preparation: allocate and initialize the storage space for static variables of the class;
Resolution: convert a symbolic reference to a direct reference;
Initialization: Initialize the Java code and static Java code block for activating static variables of the class.
Attributes in the initialization class are commonly used for static code blocks, but can only be used once.

(2) initialization sequence 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 (*)}}

Q: When the statement (*) is executed, what is the order of the printed results? Why?
A: When the statement (*) is executed, the result is printed in the following order:

 parent static blockchild static blockparent blockparent constructorchild blockchild constructor

  

Analysis: when new child () is executed, it first checks whether there is a static code block in the parent class. If yes, it first executes the content in the static code block in the parent class, after the content in the static code block of the parent class is executed, execute the static code block in the subclass (own class). After the static code block of the subclass is executed, it then checks whether the parent class has non-static code blocks. If yes, it executes non-static code blocks of the parent class. The non-static code blocks of the parent class are executed, and then the construction method of the parent class is executed; after the constructor of the parent class is executed, it goes on to check whether the Child class has non-static code blocks. If so, it executes the non-static code blocks of the Child class. After the non-static code block of the subclass is executed, the constructor of the subclass is executed. This is the initialization sequence of an object.

Summary:
Object initialization sequence: first, execute the static content of the parent class. After the static content of the parent class is executed, execute the static content of the Child class. After the static content of the Child class is executed, check whether the parent class has non-static code blocks. If yes, execute the non-static code blocks of the parent class. After the non-static code blocks of the parent class are executed, execute the construction method of the parent class; after the constructor of the parent class is executed, it goes on to check whether the Child class has non-static code blocks. If so, it executes the non-static code blocks of the Child class. The non-static code block of the subclass is executed before the subclass constructor is executed. In a word, the content of the static code block is first executed, followed by the non-static code block and constructor of the parent class, and then the non-static code block and constructor of the subclass are executed.

Note: No matter whether the constructor includes any parameter or not, the constructor of the subclass first searches for the constructor without parameters of the parent class. If the parent class does not have a constructor without parameters, the subclass must use the supper key child to call the constructor with parameters in the parent class. Otherwise, the compilation fails.

Related Article

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.