Static correlation of Java4android

Source: Internet
Author: User

In this section, I want to relate to the Java static knowledge points all involved, at least when you read this post, your knowledge of Java static can let you in the gossip can chat with other programmers for a while.
Static in Java is mainly divided into: static member variables, static member functions, static code snippets, static classes. Let's make a word.
This article is organized as follows, first of all, we explain the difference between static and non-static, and then we are specific to the above static related knowledge points.


1, the difference between a static object and a non-static object


The difference between static and non-static is shown in the table below

Compare Items Static non-static
Owning property Is the kind of co-owned is owned independently by the class objects.
Memory allocation The memory space is fixed. Space is allocated within each of the subordinate classes
Allocation order Allocate space for static objects first Then allocate space for non-static objects, that is, the initialization order
is static and non-static first.

The benefits of static objects:

1) The data of the static object is unique in the whole world, and the change is changed. If you want to deal with something that is unique throughout the program, it's a good way to get static. Non-static things you modify later just modify his own data, but will not affect other similar objects of data;
2) Easy reference. Use the class name directly. static method name or class name. Static variable names can be referenced and directly modify their property values without the Get and set methods;
3) Maintain the uniqueness of the data. This data is unique globally, modifying any of his places, where all the applications are used will be reflected in the changes to the data. Effective reduction of unnecessary waste;
4) Static final is used to modify member variables and member methods, which can be simply understood as "global constants". For a variable, it means that once the value is given, it cannot be modified;
5) Static, it's not a good object-oriented idea, if you find yourself using too much static, the design is a problem.


2, static member variable

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. You can create such a member by adding the keyword 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 refer to any object (regardless of whether the class has static adornments).

3, static Member method
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. The method declared as static has the following limitations: •
1) They can only invoke other static methods
2) They can only access static data
3) They cannot refer to this or super in any way (this relates to objects, super is related to inheritance)

4, Static code block
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 such as the main method must be static this is the difference between the program portal is: Static code block is automatically executed, static method is called when it is executed.


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

Class load Order:


In Java, the class loader to load a class into a Java virtual machine, to go through three steps to complete: loading, linking and initialization, wherein the link can be divided into the verification, preparation and parsing three steps, in addition to parsing, the other steps are strictly in order to complete, the main work of each step is as follows:


Loading: Finding and importing binary data for classes or interfaces;
Link: Perform the following validation, preparation and resolution steps, where the parsing step is optional;
Checksum: Check the correctness of binary data of imported class or interface;
Prepare: Allocate and initialize storage space for static variables of class;
Parsing: The symbolic reference is converted to a direct reference;
Initialize: Initializes the Java code and static Java code blocks of the static variables of the class.
Initializing a property in a class is a common use of static code blocks, but only once.

Example 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 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 in 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.


5, Static class


In general, it is not possible to modify a class with static. If you must modify the class with static, static is usually used to decorate the anonymous inner class.
Create another class in one class, called the member inner class. This member inner class can be static (with the static keyword decorated), or it can be non-static. Since static internal classes are defined and used, there are various limitations. So there is not much to be used in the actual work.
In the development process, the most or non-static member inner class used in the inner class. However, in certain situations, static internal classes can also play a unique role.

1) Purpose of static class use

When defining an inner class, you can precede it with a permission modifier static. At this point, the inner class becomes a static inner class. However, due to various reasons, such as the use of restrictions and other factors (specific use restrictions, the author will elaborate in the following content), in the actual work is not a lot. But it is not that it has no value. In some special cases, the lack of this static inner class is really not good. If you are setting up a main method in each Java source file (the main method is the portal of an application and must have one), there will be a lot of extra code when you are testing the code program. And most of the time, the code for the main program is just a form for a Java file, and it doesn't need the main method itself. But the main method is less than the absolute. In this case, the main method can be written to a static inner class, eliminating the need to set a similar main method for each Java source file. This is very useful for code testing. In some of the large-scale application development, it is a common technical means. For this reason, the static inner class is less common, but the program developer has to master it. Maybe at some critical moment, it can also play a huge role.

public class Maininstaticclass {  static class main{static void Main () {//Writes the Main method to a static inner class, thus eliminating the need for each source file to have a similar main method new Maininstaticclass (). 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 MAININSTATICC Lass (). print (); MainInStaticClass.Main.main (); new Maininstaticclass.main ();} }


2) Restrictions on the use of static internal classes

Defining an inner class as a static class is basically the same as defining other classes as static classes, and the reference rules are basically consistent. However, the details are still very different. Specifically, there are a number of places to draw the attention of the developers of the program.


One is the definition of static members, including static and static members. In general, if an inner class is not defined as a static inner class, it cannot be defined as a static member variable or a static member method when defining a member variable or a member method. In other words, static members cannot be declared in non-static inner classes. If an inner class age is now defined in a student class, it is not defined as a static class if the class is not decorated with the static keyword, so it is not allowed to use the static keyword to decorate a member method or member variable in this inner class. It's not going to work at compile time. Therefore, the program developers need to note that only an inner class is decorated as a static class, then you can define static member variables and member methods in this class. This is an attribute of the static inner class. It is for this reason that sometimes less of this static internal class, a lot of work can not be completed. Or to go around a big circle in order to achieve the needs of a user. This is also an important reason for the existence of static internal classes.


After note: After everyone's correction, now declare: Non-static inner class can also define static members but need to have a final keyword modification, static method in view of the inability to use the final decoration, still must be defined in a static inner class or non-intrinsic class.


Second, there is a larger limit on the members ' references. A general non-static inner class that can arbitrarily access member variables and member methods in an external class. Even if these member methods are decorated as private (a proprietary member variable or method), their non-static inner classes are freely accessible. is a non-static inner class privilege. Because member variables that are defined as private are inaccessible in other classes or methods. However, if an inner class is defined as static, there are a number of limitations when Silver uses the member method of the outer class or the member variable. Non-static members of external classes (including member variables and member methods) cannot be accessed from objects in the static inner class. What does that mean? If you define two variables in an external class, one is a non-static variable, and one is a static variable. In a static inner class, it is only possible to refer to static variables in the outer class, whether within the member method or elsewhere, without accessing non-static variables. In a static inner class, you can define a static method (and only static methods can be defined in a static inner class), referencing the members of an external class in a static method. However, there is one common denominator, regardless of where the inner class is referenced, that only static member methods or member variables in the outer class can be referenced. For non-static member variables and member methods, it is inaccessible in static inner classes. This is the maximum usage limit for static internal classes. There is no such restriction in ordinary non-static inner classes. It is for this reason that the static inner class is used only in some specific situations. Its scope of application is far from as wide as that of non-static internal classes.


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


In general, when creating a member's inner class in a class, there is a mandatory requirement that an instance of an inner class be bound to an instance of an external class. That is, before you create an inner class, you need to use the New keyword in the outer class to create an object of the inner class. In this case, if an inner class object is initialized from an external class, the inner class object is bound to the outer class object. In other words, the object of the ordinary non-static inner class is attached to the outer class object. However, if a member developer creates a static inner class, then this is another matter. Typically, when a programmer defines a static inner class, it is not necessary to define a binding on an instance of an external class. That is, to define a static inner class in an external class, you do not need to use the keyword new to create an instance of the inner class. That is, when you create a static class inner object, you do not need an object of its outer class.


New Maininstaticclass.main ();



Specifically why this, the general program developers do not need to know so deep, just remember that there is this rule. When defining static internal classes, do not make the superfluous mistake.


From the above analysis, it can be seen that static internal classes and non-static internal classes are still very different. As a general program developer can understand, a non-static inner class object implicitly stores a reference in an external class, pointing to the outer class object that created it. Regardless of this understanding, program developers need to keep in mind the differences between static internal classes and non-static inner classes. If you can create static member methods with member variables (static inner classes can create static members rather than static inner classes are not available), restrictions on accessing members of external classes ( Static inner classes can only access static member variables in external classes and member methods, but not static inner classes that can access static or access non-static external class member methods and member variables. These two differences are the biggest differences between static inner classes and non-static external classes, and are the reason why static inner classes exist. After understanding this discrepancy, the program developer also needs to know when to use static internal classes. In order to avoid writing the code of the Main method in the various Java source files, you can write the main method to the static inner class to reduce the amount of code written and make the code more concise, as in the case of program testing.
In summary, static inner classes are a very special class in the Java language, and differ greatly from normal static classes and non-static inner classes. As a program developer, it is important to know the differences between them and to apply the appropriate classes in the right places in the actual work. In general, however, the use of static internal classes is not very high. But on some occasions, if there is no such internal static class, it may play a less effective negative effect

Reference and reprint:

[1] static class: Http://blog.sina.com.cn/s/blog_605f5b4f0100zbps.html

[2] Static code block: http://www.cnblogs.com/panjun-Donet/archive/2010/08/10/1796209.html

[3] Static variables, methods and blocks: http://blog.csdn.net/zhandoushi1982/article/details/8453522










Static correlation of Java4android

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.