Description: In Java we often use the static keyword, which is the equivalent of a global variable (a static variable or a class variable).
(1) When you add static to a method or variable in a class, the method or variable is only ' A ', in the various objects of the subsequent class also share a copy of this static modified method or variable (directly accessed through the class name), compared to the other non-static variables in the parent class or method, when its object is produced, the object will itself back up a non-static variable or method (shared by all instances of the class) 。 So from this point of view, static can actually save memory space, but will always occupy memory space until the program exits memory.
(2) A non-static method cannot be called in a static method, and a non-static method can invoke either a static method or a variable or a non-static method or a variable.
(3) A static code block is represented by a statically decorated code block, which executes the code block when the Java Virtual Machine (JVM) loads the class (very useful).
(4) It is common to use static variables when you need to implement the following two functions: when you share values between objects, and when you make it easier to access variables.
code example:
public class Teststatic {int A; double b; static int c; static double D; public static void Test () {//b=2;//error: Because the static party The method cannot call a non-static variable c = 3;//static method can of course call the static variable System.out.println ("Reference static variable succeeds!") "+" C "+" = "+ c);} public static void Main (string[] args) {//TODO auto-generated method Stub teststatic.d = 5.6;//call static variable directly through class System.ou T.println (TESTSTATIC.D); Teststatic.test ();//indicates that a static method or variable belongs directly to a class property and can be called directly without the need to call through an object. }}
Attach the static memory analysis diagram:
? ?
Talking about the static keyword in Java