Java basics of the keyword static detailed

Source: Internet
Author: User
Tags modifier static class

One, static variable

The member variable decorated by the static keyword is called a static variable, and before we talk about the difference between a member variable and a local variable, what is the difference between a static variable and a member variable?

1. Calling mode


Static variables: class variables, which can be invoked directly through the class name, or by the object name, which belongs to the class
Member Variable: instance variable, only called by object name, this variable belongs to object
2, storage location
Static variables: Static areas stored in the method area
Member variables: storing in heap memory
3. Life cycle
Static variables: exist as classes are loaded, disappearing as classes disappear
Member variables: exist as objects are created and disappear as objects disappear
4, with the object of relevance
Static variables: Data shared by all objects, with only one copy in memory
Member variables: Each object is unique to the data, in memory there are multiple replicas, each of the replicas do not affect

After reading the above points, we think about when we use static to modify our variables, and from the 4th we can see that when we define variables that are shared by all instances, we can use static to modify them, for example, each of us has a nationality, usually the nationality is China, So this time we can use static to modify

1 package demo;
2
3 public class Person {
4 private String name;
5 private int age;
6 private static String nationality = "China";
7
8...
9}
So when you construct the person class, you don't have to allocate the memory space to nationality this property every time, there is only one copy in memory, and each instance object points to it, when one of them changes the value of the nationality variable. The nationality value of other objects changes as well.

Second, static method

The Member method modified by the static keyword is called a static method, and see our most common Main method

1 package demo;
2
3 public class Maindemo {
4 public static void main (string[] args) {
5 System.out.println ("Main method");
6}
7}
The code does not construct a Maindemo object, but the running program prints the main method in the console, an example that shows that static methods are better than objects and exist, like static variables, when class loads, so What happens if we call non-static and Non-static methods in a static method, and look at the following code

1 package demo;
2
3 public class Maindemo {
4 private String name;
5 private static String address;
6
7 public static void Main (string[] args) {
8 Show1 (); Cannot make a static reference to the Non-static method
9//Show1 () from the type Maindemo
Ten Show2 ();
11}
12
private void Show1 () {
SYSTEM.OUT.PRINTLN (name);
SYSTEM.OUT.PRINTLN (address);
16}
17
private static void Show2 () {
SYSTEM.OUT.PRINTLN (name); Cannot make a static reference to the
//non-static Field name
SYSTEM.OUT.PRINTLN (address);
22}
23}
The 8th and 19th lines in the code do not complain, the error message is already commented on the right side of the code, because the static method is already in memory when the class is loaded, the object does not exist, so the non-static variable cannot be accessed in the static method, and the non-static variable exists in the heap space when the object is created. How can a nonexistent thing access the same reason why non-static methods cannot be accessed in static methods? Since non-static methods are shared by all instances, the method is also class-owned, which can naturally be invoked by the class name

1 package demo;
2
3 public class Maindemo {
4 private static String address;
5
6 public static void main (string[] args) {
7 maindemo.show ();
8}
9
Ten private static void show () {
One System.out.println (address);
12}
13}
third, static code block

A static block can be placed anywhere in a class, and there can be more than one static block in a class. As with member variables, member methods, static blocks of code exist in memory at the time the class is loaded, and when the class is first loaded, the JVM executes each static block in the order of the static block and executes it only once, which in turn increases the point performance.

 1 Package demo;
 2
 3 public class Staticdemo {
 4     private static String address = "C Hina ";
 5
 6     static {
 7          SYSTEM.OUT.PRINTLN ("A-static block");
 8    }
 9
10     static {
11         System.out.println ("second static Block");
12    }
$
14     public static void Main (string[] args) {
15     & nbsp;   staticdemo.show ();
16    }

18     private static void Show () {
19       & nbsp SYSTEM.OUT.PRINTLN (address);
20    }
21}
Output Results:

The I-static block
Second static block
Of
From the above we summarize some of the following characteristics of the static keyword:

1, static can be used to modify the member variables, member methods, static code block;

2, with the class loading and loading, takes precedence over the object, is shared by all objects, can be called directly by the class name (recommended), and, of course, by an instance invocation, although the copy in memory is only one, but the life cycle is long and the static space is released when the class is reclaimed;

3, static methods can only access static variables and static members;

4. When all objects share a certain data, this member variable is defined as static;

5. Static code blocks are executed only once.

Add

1. Static method
Typically, you define a method as static in a class, that is, you can call this method without an object of this class
The methods declared as static have 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.
Class Simple {
static void Go () {
System.out.println ("Welcome");
}
}

public class Cal {
public static void Main (string[] args) {
Simple.go ();
}
}
Calling a static method is the "class name. Method Name", and the use of static methods is simple as shown above. In general, static methods often provide utilities for other classes in the application, and a large number of static methods are defined for this purpose in Java's class libraries.

2. Static variables
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. Static variables are similar to static methods. All such instances share this static variable, that is, when the class is loaded, only one storage space is allocated, and all objects of this class can manipulate this block of storage, of course, for final.
Class Value {
static int c = 0;

static void Inc () {
C + +;
}
}

public class Count2 {
public static void Prt (String s) {
System.out.print (s);
}

public static void Main (string[] args) {
Value v1, v2;
V1 = new Value ();
v2 = new Value ();
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
V1.inc ();
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
}
}
The results are as follows: V1.c=0 v2.c=0 v1.c=1 v2.c=1
This can prove that they share a storage area. A static variable is somewhat similar to the concept of a global variable in C.

It is worth discussing the initialization problem of static variables.
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:
Class Value3 {
static int c = 0;

Value3 () {
c = 15;
}

VALUE3 (int i) {
c = i;
}

static void Inc () {
C + +;
}
}

public class Count {
public static void Prt (String s) {
System.out.println (s);
}

Value3 v = new Value3 (10);
Static VALUE3 v1, V2;
static {//This is a static block
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
V1 = new Value3 (27);
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
v2 = new Value3 (15);
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
}

public static void Main (string[] args) {
Count ct = new count ();
PRT ("ct.c=" + ct.v.c);
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
V1.inc ();
PRT ("v1.c=" + v1.c + "v2.c=" + v2.c);
PRT ("ct.c=" + ct.v.c);
}
}

The result is: v1.c=0 v2.c=0
V1.c=27 v2.c=27
V1.c=15 v2.c=15
ct.c=10
v1.c=10 v2.c=10
V1.c=11 v2.c=11
ct.c=11
This program shows the various features of static initialization. If you first touch Java, the result may surprise you. It may be confusing to add parentheses after static. The first thing to tell you is that the static-defined variable takes precedence over any other non-static variable, regardless of the order in which it appears. As shown in the program, although v appears in front of V1 and v2, the result is V1 and V2 initialization in front of v. Following the static{followed by a code that 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 understand the static keyword. When it comes to inheritance, the static variables of the parent class are initialized, followed by subclasses, and so on.

3. Static class
Typically, a generic class is not allowed to be declared static, and only one inner class is available. At this point, the internal class declared as static can be used directly as a normal class, without the need for an instance of an external class.
public class Staticcls {
public static void Main (string[] args) {
Outercls.innercls oi = new Outercls.innercls ();
}
}

Class Outercls {
public static class Innercls {
Innercls () {
System.out.println ("Innercls");
}
}
}
The result is: innercls

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.

5. Add:
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 you declare an object of its class, you do not generate a copy of the static variable, 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 cannot be referenced directly by 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).

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

static method
Static methods can be invoked directly through the class name, and any instance can be invoked, so static methods cannot use the This and Super keywords, and cannot directly access 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 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.

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.