Static variables and static methods
- Static variable
Static variables (class variables) are global variables that can be shared among object instances.
class ABCD{ char data; static int share_data;}class StaticDemo{ ABCD a,b,c,d;}
The above four objects A, B, C, and D share the static variable pai_data.
The lifetime of static variables does not depend on objects. Other classes can access them without instantiation:
public class StaticVar{ public static int number = 5;}public class OtherClass{ public void Method() { int x = StaticVar.number; // here }}
Static Method
Static methods are equivalent to global functions in C language. Other classes call them without instantiation, just like static variables.
We know that global variables can be divided into instance variable and static variable. Likewise, methods can be divided into instance methods and static methods (with the static keyword). When using variables, pay attention to the following rules:
Instance methods can use both instance variables and class variables;
Static methods can only use class variables, but cannot directly use instance variables.
- When a value is assigned to a static variable, the value of the variable is the value after the last value is assigned to the variable during the program running.
private void TestValue(){ static int num = 1; num++;}
After the method is called for the first time, the value of num in the memory is 2, and the value after the second call is 3.