About the static keyword for Java

Source: Internet
Author: User

Generally speaking, when you create a class, you are describing the appearance and behavior of the object of that class. Unless you create the object of that class with new, you don't actually get anything. When you create an object with new, the data storage space is allocated and its methods are called by the outside world.

However, there are two situations in which the above method cannot be solved. One scenario is that you only need to allocate a single storage space for a particular piece of data , regardless of whether you want to create a pair of objects, or even do not need to create any objects at all. Another scenario is that You want a method to not be associated with any object that contains its class. That is, you can call this method even if you do not create an object .

The static keyword can be used to meet both of these needs. When you declare that a thing is static, you assume that the data or method is not associated with any object instance of the class that contains it. So even if you never created any objects of a class, You can also call its static method or its static data. Typically, you must create an object and use it to access data or methods. Because non-static data and methods must know the specific objects they work with. Because you do not need to create any objects before using the static method, for a static method, you cannot simply access a non-static member or method by calling another method without specifying an object, because a non-static member or method must be associated with a particular object.

A. Static Modification method

In general, defining a method in a class is static, which means that you do not need an object of this class to call this method

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.

1. You can invoke the static adornment method without creating an object of the class:

Class Simple {public static void Show1 () {System.out.println ("hello!");} public void Show2 () {System.out.println (' nice! ');}} public class Staticmethod {public static void main (string[] args) {simple.show1 ();//simple.show2 (); Error}}

In the above code, the Show1 () method in simple is static, and the Show2 () method is the general method, so in the main method, the Show1 () method can be called directly through the Simple.show1 ().

2. The static modified method can only invoke other static methods:

Class Simple {static void Show1 () {//hello ();//Cannot call Hi ();} public void Hello () {System.out.println ("Hello");} public static void Hi () {System.out.println ("Hi");}} public class Staticmethod {public static void main (string[] args) {Simple.show1 ();}}

3. Use static modifiers to intelligently access static data:

Class Simple {int i = 5;static int j = 8;static void Show1 () {//system.out.println ("hello!" + i);//cannot call non-static data}static V OID Show2 () {System.out.println ("hello!" + j);}} public class Staticmethod {public static void main (string[] args) {simple.show1 (); Simple.show2 ();}}
4. The static-modified method cannot refer to this or super in any way:
Class Simple {private int n; static void Show1 (int n) {//THIS.N = n; Cannot reference This}}public class Staticmethod {public static voi D main (string[] args) {Simple.show1 (8);}}

Invoking a static method is "class name. Method Name", and the use of static methods is simple as shown above. In general, static methods are often used by other classes in the application, and in Java's class libraries a large number of static methods are defined for this purpose.

Second, static modifier variable

1. Static variables share a block of storage

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. Static variables are similar to static methods. All such instances share this static variable, that is, when a class is loaded, only one storage space is allocated, and all objects of this class can manipulate this block of storage space, of course, for final.

Class Value {static int c = 0;static void Add () {C + +;}} public class Staticmethod {public static void main (string[] args) {Value v1,v2;v1 = new value (); v2 = new value (); System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c); V1.add (); System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c);}}

Operation Result:

v1.c = 0---v2.c = 0
V1.C = 1---v2.c = 1

This can prove that they share a piece of storage.

2. Initialization of static variables

Class Value {static int c = 0; Value () {c = 15;} Value (int i) {c = i;} static void Add () {C + +;}} public class Staticmethod {Value v = new value (ten); static Value v1,v2;static {System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c); v1 = new Value (47); System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c); v2 = new Value (15); System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c);} public static void Main (string[] args) {Staticmethod method = new Staticmethod (); System.out.println ("METHOD.C =" + method.v.c); System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c); V1.add (); System.out.println ("v1.c =" + v1.c + "---" + "v2.c =" + v2.c);; System.out.println ("METHOD.C =" + Method.v.c);}}

Operation Result:

v1.c = 0---v2.c = 0
v1.c =---v2.c = 47
v1.c =---v2.c = 15
METHOD.C = 10
V1.C = Ten---v2.c = 10
V1.C = one---v2.c = 11
METHOD.C = 11

The first thing to tell you is that the variables defined by static take precedence over any other non-static variables, regardless of the order in which they appear. As shown in the program, although v appears in front of V1 and v2, the result is the initialization of V1 and V2 in front of v. followed by a piece of code behind static{, which is used for explicit static variable initialization, which is initialized only once, and when the class is first loaded. If you can read and understand this code, it will help you to understand the static keyword. When it comes to inheritance, the static variables of the parent class are initialized first, then the subclasses, and so on.

Third, static modified class

Usually a normal class is not allowed to be declared static, only one inner class can. In this case, the static inner class can be used directly as a normal class, without the need to instantiate an external class.

public class Staticclass {public static void main (string[] args) {Outercls.innercls Oi = new Outercls.innercls ();//OUTERCL S.test ot = new outercls.test (); error}}class outercls {public static class Innercls {public Innercls () {System.out.println ("I Nnercls ");}} public class Test {public test () {System.out.println ("Test");}}}

Operation Result:

Innercls

Iv. use of static and final piece

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.

V. Summary

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 you declare objects of its class, you 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).
Static variable
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).
static method
Static methods can be called directly from the class name, and any instance can also be called, so a static method cannot use the This and Super keywords, and cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static). Only static member variables and member methods of the owning class can be accessed. 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.

Execution Priority:

Static code block initialization----Default initialization------Display initialization------Construction code block initialization----constructor initialization

About the static keyword for 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.