The role and usage of the static keyword in Java detailed introduction _java

Source: Internet
Author: User
Tags modifier

static denotes "global" or "static" meaning, used to decorate member variables and member methods, or to form static-code blocks, but the concept of global variables is not available in the Java language.

The member variables and member methods that are decorated by static are independent of any object of the class. That is, it does not rely 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 runtime 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 both global and global methods, and when declaring the object city of its class, a copy of the static variable is not generated, but all instances of the class share the same static variable.

A static variable can have a private modifier before it it is important to indicate that this variable can be used in a static code block of a class, or in other static member methods of a class (which can, of course, be used in non-static member methods-nonsense), but it is not possible to refer directly to the class name in other classes. In fact, you need to understand that private is the access permission limit, static means not instantiated can be used, so easy to understand more. The effect of the preceding static plus the other access rights keyword is also so.

The member variables and member methods of the static modifier are customarily called 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 code block decorated with static is a block of static code that is executed when the Java Virtual Machine (JVM) loads the class (very useful, hehe).

1. Static variable

There are two types of class member variables that are statically modified: a static variable or a class variable, or a variable that is not modified by static, called an instance variable.

The difference between the two is:

For static variables in memory only one copy (save memory), the JVM only for static allocation of memory, in the process of loading classes to complete the memory allocation of static variables, the use of the class name direct access (convenient), of course, can also be accessed through the object (but this is not recommended).

For an instance variable, no instance is created, and the instance variable is allocated once in memory, and the instance variable can have multiple copies in memory, with no effect (flexibility).

So you typically use static variables when you need to implement the following two features:

1. When sharing values between objects
2). For easy access to variables

2. Static method

Static methods can be invoked directly through the class name, and any instance can be invoked,

Therefore, you cannot use the This and super keywords in static methods, you cannot directly access instance variables and instance methods of the owning class (that is, member variables and member methods without static), you can only access static member variables and member methods of the owning class.

Because instance members are associated with a particular object! This need to understand, to understand the truth, not memory!!!

Because the static method is independent of any instance, the static method must be implemented, not abstract.

For example, for easy invocation of the method, all methods in the math class in the Java API are static, while the static method inside the generic class is also convenient for other classes to invoke the method.

Static method is a kind of special method inside class, the corresponding method is declared static only when need, the method of a class is generally non-static

3. Static code block

A static code block is also called a code block, which is a static block of statements that is independent of class members in a class, can have multiple, can be positioned casually, it is not in any method body, and the JVM executes these static blocks of code when it loads classes, if there are multiple static code blocks, The JVM executes them sequentially in the order in which they appear in the class, and each block of code 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 automatically generates method stubs  
}  
static{  
test5.a=5;  
System.out.println (a);  
}  
public void F () {  
System.out.println ("Hhahhahah");  
}  

Run Result:
3
Hhahhahah
1000
4
5

Static blocks of code can be assigned to some static variables, and finally take a look at these examples, a static main method, so that the JVM when running the main method can be called directly without creating an instance.

4. What does the static and final piece mean?

Static final is used to decorate member variables and member methods, which can be easily understood as "global constants"!

For a variable, it means that once the value is not modifiable, it can be accessed through the class name.

For methods, they are not overwritten and can be accessed directly through the class name.

Sometimes you want to define a class member so that its use is completely independent of any object of that class. Typically, a class member must be accessed through the object of its class, but you can create a member that can be used by itself without reference to a particular instance. You can create such a member by preceding the declaration of the member with the keyword static (static). If a member is declared static, it can be accessed before any object of its class is created without reference to any object. You can declare both the method and the variable as static. The most common example of a static member is main (). Because main () must be invoked when the program starts executing, it is declared static.

A variable declared as static is essentially a global variable. When an object is declared, it does not produce a copy of the static variable, but all instance variables of the class share the same static variable. The methods declared as static have 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 (the keyword super is related to inheritance, as described in the next chapter).

If you need to initialize your static variable by calculation, you can declare a static block that 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:

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;  
}  
}


Once the Usestatic class is loaded, all static statements are run. First, A is set to 3, then the static block executes (prints a message), and finally, B is initialized to a*4 or 12. Then call Main (), and main () calls meth (), passing the value 42 to X. 3 println () statements refer to two static variables A and B, and local variable x.

Note: It is illegal to refer to any instance variable in a static method.

The following is the output of the program:

Copy Code code as follows:

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

Outside of the class that defines them, static methods and variables can be used independently of any object. So you just add the number operator to the name of the class. For example, if you want to invoke a static method from outside the class, you can use the following generic format:
Copy Code code as follows:

Classname.method ()

Here, ClassName is the name of the class that defines the static method in the class. As you can see, this format is similar to the format of calling a non-static method with an object reference variable. A static variable can be accessed in the same format-the class name is dotted with the number operator. This is a controlled version of how Java implements global functionality and global variables.

Here is an example. In main (), the static method CallMe () and static variable B are accessed outside their classes.

Class Staticdemo {  
static int a =;  
static int b =;  
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 following is the output of the program:

Copy Code code as follows:

A = 42
b = 99

A static member cannot be accessed by an instance created by its own class.

If a member that is not modified by static is an object member, it is owned by each object.

A member of a static modifier is a class member, which can be called directly by a class and is common to all objects.

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.