[Static keyword in Java foundation]java

Source: Internet
Author: User

1.static concept

Static modifier, what is static modifier? As you know, any variable or code in the program is automatically allocated by the system at compile time to store the memory, and so-called static refers to the memory allocated after compilation will persist until the program exits the memory will release the space, that is, as long as the program is running, then this memory will always exist.

What is the point of doing this? In a Java program, everything is an object, and an object's abstraction is a class, and for a class, if you want to use his members, you would normally have to instantiate the object before you can access those members by reference to the object, but there is an exception. Is that the member is declared with static (in this case, exclude the access control of the Class), you can let the user do not need to instantiate the object can reference members, Java has many classes declared static, the most basic is Integer.parseint (), Float.parsefloat ( etc.) to convert the object to the basic data type you want. Such variables and methods are also called class variables and class methods.

Static classes, static methods, static variables, and static blocks are used.

2. Static methods and static members

The static method is generally called a static method, because static methods can be accessed without relying on any object, so for a static method it cannot be used in a method because it is not attached to any object, and since there are no objects, this is not the case. And because of this feature, non-static member variables and non-static member methods of the class cannot be accessed in a static method, because non-static member methods/variables must be dependent on a specific object to be able to be called. It is important to note, though, that non-static member methods and non-static member variables cannot be accessed in static methods, but static member methods/variables are accessible in non-static member methods.

 Public classStaticmethod { Public intage=10;  Public StaticString name = "Hello Static";  Public voiddisplay () {System.out.println (age); SYSTEM.OUT.PRINTLN (name);//static variables can be accessed by non-static methods    }         Public Static voidShow () {//System.out.println (age);--Non-static variables cannot be accessed in static methodsSystem.out.println (name); }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubStaticmethod.show ();//calling a static method without creating an object is called directly    }}

(1) What is the difference between a Java static object and a non-static object? (Reference: http://blog.csdn.net/zhandoushi1982/article/details/8453522)

The comparison is as follows:

Static Object Static Object
Owning property: The class has a common ownership of the class objects independently
Memory allocation: a fixed amount of space is allocated in each subordinate class
Allocation Order: Allocates the space of the static object and then allocates the space to the non-static object, that is, the initialization order is first static and non-static.

(2) What are the benefits of Java static objects?

    • The data of the static object is unique in the global, and changed. If you want to deal with something that is unique throughout the program, it's a good way to get static. A non-static thing you modify later only modifies his own data, but does not affect the data of other homogeneous objects.
    • Easy reference. use the class name directly. static method name or class name. A static variable name can be referenced and can modify its property values directly, without the get and set methods.
    • Keep the data unique. 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. Effectively reduce unnecessary waste.
    • Static final is used to modify member variables and member methods, which can be simply understood as "global constants." For a variable, the value is not modifiable once it is given, and for a method, it is not overwritten.

(3) Static variables, static methods and static blocks

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).

You can declare methods and variables as static. The most common example of a static member is main (). There are several limitations to the method declared as static (main is also??). ): ·

    • They can only invoke other static methods.
    • They can only access static data
    • They cannot refer to this or super in any way (this relates to objects, super is related to inheritance)

Example: a Static block 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.

 Public classTestnew {02.Static intA = 3; 03.Static intb; 04.Static voidMethintx) {  System.out.println ("x =" +x); System.out.println ("a =" +a); System.out.println ("b =" +b); 08. }  09.Static {  System.out.println ("Static block initialized"); One. B = a*4; 12. }  13. Public Static voidMain (string[] args) {14.//TODO auto-generated Method StubMeth (42); 16. }  17.}

The execution results are:

Static block initialized
x = 42
A = 3
b = 12

The order of execution of the class testnew is: First the static block executes (prints a message), A is set to 3, and the last B is initialized to a*4 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.

3. Static block (see code block section)  


4 Static Inner class

In general, Java is not allowed to modify classes with static. If you must modify the class with static, static is usually used to decorate the anonymous inner class.

Sometimes, an inner class is used only to hide a class inside another class, and you do not need an inner class to reference a perimeter object, so you can declare an inner class as static in order to cancel the resulting reference.

 Packagestatictest; Public  classStaticclass { Public Static classPair//methods and member variables of static inner classes can be non-static, but static inner classes cannot reference non-static member variables and methods of external classes    {        Private DoubleFirst ; Private Doublesecond;  PublicPair (DoubleFirstDoublesecond) {             This. first=First ;  This. second=second; }                 Public DoubleGetFirst () {returnFirst ; }    }         Public StaticPair Minmax (Double[] values) {        Doublemin=Double.max_value; Doublemax=Double.min_value;  for(Doublev:values) {            if(v<min) min=v; if(V>max) max=v; }                return NewPair (min, max); }         Public Static voidMain (string[] args) {Staticclass.pair Pair= Staticclass.minmax (New Double[]{1.7,2.5,3.3,100}];//Staticclass do not create objects directly through the. Referencing inner classes    }}

Reference: http://blog.sina.com.cn/s/blog_605f5b4f0100zbps.html

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 use of static internal classes
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. 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.

  2) Use restrictions for static internal classes
defines an inner class as a static class, as is the method for 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 a static member, 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. (Special case: A non-static inner class can also define a static member but need to have a final keyword adornment at the same time, whereas a static method must still be defined in a static inner class or non-intrinsic class, given that it cannot be decorated with a final.)
The second is on the member's reference, there is a relatively large limit. 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. However, if an inner class is defined as static, non-static members of the outer class (including member variables and member methods) cannot be accessed in the object of the static inner class.

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, 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 create an inner class object by using the outer class. Inner class object name.
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. 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.

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

[Static keyword in Java foundation]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.