Static correlation of Java4Android

Source: Internet
Author: User

Static correlation of Java4Android

In this section, I want to involve all the knowledge points related to Java Static, at least after reading this post, your static understanding of Java allows you to chat with other programmers after meals.
Static in Java is mainly divided into: static member variables, static member functions, static code segments, static classes. Let's talk about it one by one.
This article is organized as follows. First, we will explain the differences between static and non-static, and then we will talk about the above static knowledge points one by one.

 

1. Differences between static and non-static objects

 

Comparison between static and non-static types is shown in the table below.

 

Compare items Static Non-static
Property Is shared by classes It is independently owned by various objects of the class.
Memory Allocation Memory space is fixed Allocate space in each ancillary class
Allocation order First, allocate space for static objects. Then allocate space for non-static objects, that is, the initialization order.
Yes. It is static first and then non-static.

 

Benefits of static objects:

 

1) the data of static objects is globally unique, and all changes are made. If you want to process something that is unique in the entire program, it is a good way to make it static. After modifying non-static objects, you only modify their own data, but it does not affect the data of other similar objects;
2) convenient reference. Directly use the class name. Static Method Name or class name. static variable name to reference and directly modify its attribute value without the get and set methods;
3) maintain data uniqueness. This data is globally unique. Modifications to any part of the data will be reflected in all the places used by the program. Effectively reduce unnecessary waste;
4) static final is used to modify member variables and member methods. It can be simply understood as a "global constant ". For variables, it means that once the value is given, it cannot be modified; for methods, it means it cannot be overwritten;
5) static: it is not a good object-oriented idea. If you find that you are using too many static resources, it indicates that the design is faulty.

 

 

2. static member variables

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 (it is irrelevant to whether the class has static modification ).

3. static member Method
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. The method declared as static has the following restrictions :·
1) They can only call other static methods
2) They can only access static data
3) They cannot reference this or super in any way (this involves objects, and super is related to inheritance)

4. Static code block
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. when a static method is loaded, it can be called directly by class name. For example, the main method must be static. The difference between the two is that static code blocks are automatically executed; static methods are executed only when they are called.


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

Class loading sequence:


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.

Sample Code:

 

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

Output result:

 

 

parent static blockchild static blockparent blockparent constructorchild blockchild constructor

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.

 

 

5. Static class

 

In general, the class cannot be modified using static. If you must use the static modifier class, the static modifier is usually an anonymous internal class.
Create another class in a class called the internal class of the member. The internal class of this Member can be static (modified using the static keyword) or non-static. Static internal classes have various restrictions during definition and use. Therefore, it is not much used in actual work.
During the development process, the most used internal classes are non-static members. However, under specific circumstances, static internal classes can also play their unique roles.

1) Purpose of static classes

When defining an internal class, you can add a permission modifier static before it. This internal class is changed to a static internal class. However, for various reasons, such as restrictions on use and so on (the specific restrictions are described in detail in the following content), not many are used in practical work. But it does not mean that it has no value. In some special cases, it is not possible to lose this static internal class. For example, during code program testing, if you set a primary method in each Java source file (the primary method is the entry to an application, which must be included ), there will be a lot of additional code. In addition, the code of this main program is only a form for Java files, and does not need this main method. However, it is absolutely impossible to lose the master method. In this case, you can write the primary method to the static internal class, so that you do not need to set a similar primary method for each Java source file. This is very useful for code testing. In some medium and large application development, it is a common technical means. For this reason, although this static internal class is not very common, it must be mastered by developers. Maybe it can play a huge role at a critical moment.

 

Public class MainInStaticClass {static class Main {static void main () {// write the Main method to the static internal class, therefore, you do not need to use a similar primary method new MainInStaticClass () for each source file (). print () ;}} public static void main (String [] args) {new MainInStaticClass (). print ();} public void print () {System. out. println (main in static inner class) ;}} public class TestMain {public static void main (String [] args) {// TODO Auto-generated method stub // new MainInStaticClass (). print (); MainInStaticClass. main. main (); new MainInStaticClass. main ();}}

 

 

2) restrictions on the use of static internal classes

Defining an internal class as a static class is basically the same as defining other classes as static classes, and the reference rules are also basically the same. However, the details are still quite different. Specifically, there are several main points to attract the attention of developers.


One is the definition of static members (including static variables and static members. Generally, if an internal class is not defined as a static internal class, when defining a member variable or member method, cannot be defined as static member variables or static member methods. In other words, static members cannot be declared in non-static internal classes. For example, if an internal class age is defined in a student class, if the class is not modified using the static keyword, It is not defined as a static class, it is not allowed to modify a member method or member variable by using the static keyword in this internal class. It won't work during compilation. Therefore, program developers must note that only by modifying an internal class to a static class can static member variables and member methods be defined in this class. This is a feature of all static internal classes. It is precisely for this reason that, sometimes, with this static internal class missing, a lot of work cannot be done. In other words, it is necessary to bypass a large circle to meet the needs of a user. This is also an important reason why static internal classes exist.


Note: after everyone's correction, we now declare that non-static internal classes can also define static members, but they need to have final keyword modifier at the same time. Static methods cannot be modified using final, it must still be defined in static or non-Internal classes.


Second, there are large restrictions on member references. Generally, non-static internal classes can access member variables and member methods in external classes at will. Even if these member methods are modified to private (private member variables or methods), their non-static internal classes can be freely accessed. It is a non-static internal Class privilege. In other classes, it is impossible to access the member variables or the method defined as private. However, if an internal class is defined as static, there will be many restrictions when Silver uses the member method of the external class or the member variable. For example, you cannot access non-static members of an external class (including member variables and member methods) from objects of static internal classes ). What does this mean? If two variables are defined in the external class, one is non-static and the other is static. In a static internal class, static variables in the external class can only be referenced inside the member method or elsewhere, but non-static variables cannot be accessed. In static internal classes, static methods can be defined (or static methods can be defined only in static internal classes), and members of external classes can be referenced in static methods. However, no matter where the internal class is referenced, there is one thing in common, that is, it can only reference static member methods or member variables in the external class. Non-static member variables and member methods cannot be accessed in static internal classes. This is the maximum usage limit for static internal classes. There is no such restriction in normal non-static internal classes. This also determines that static internal classes are only used in some specific scenarios. Its application scope is far from as wide as non-static internal classes.


Third, when creating a static internal class, you do not need to bind the instance of the static internal class to the instance of the external class.


Generally, when creating a member internal class in a class, there is a mandatory rule that the instance of the internal class must be bound to the instance of the external class. That is to say, before creating an internal class, you must use the new keyword in the external class to create the object of this internal class. In this case, if an internal class object is initialized from an external class, the internal class object will be bound to the external class object. That is to say, objects of common non-static internal classes are attached to external class objects. However, if a member developer creates a static internal class, this is another matter. Generally, when defining static internal classes, programmers do not need to define instances bound to external classes. That is to say, to define a static internal class in an external class, you do not need to use the keyword new to create an instance of the internal class. That is, when creating a static class internal object, you do not need the object of its external class.


New MainInStaticClass. Main ();



The specific reason is as follows. Generally, developers do not need to understand this details, but remember to have this rule. Do not make mistakes when defining static internal classes.


From the above analysis, we can see that static internal classes are quite different from non-static internal classes. Generally, program developers can understand that a non-static internal Class Object implicitly stores a reference in the external class and points to the external class object that creates it. With this understanding, developers must remember the differences between static and non-static internal classes. For example, whether static member methods and member variables can be created (static internal classes can be created but not static internal classes) limitations on access to members of external classes (static internal classes can only access static member variables and member methods in external classes, rather than static internal classes. static external class member methods and member variables ). These two differences are the biggest differences between static internal classes and non-static external classes, and are also the reason why static internal classes exist. After understanding the difference, the program developers also need to know under what circumstances should they use static internal classes. For example, during program testing, to avoid writing the code of the main method in each Java source file, you can write the main method into the static internal class to reduce the amount of code writing, make the code more concise.
In short, static internal classes are a special class in the Java language, which is very different from common static classes and non-static internal classes. As a program developer, you must know the differences between them and adopt appropriate classes in the actual work. But in general, the usage frequency of static internal classes is not very high. However, in some cases, if this internal static class is not used, it may play a negative role.
 

 



 

 

 

 

 

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.