static Modifiers can be associated with variables 、 Methods used together , Said is “ static state ” Of .
Static variables and static methods can be accessed through class names , There is no need to create an object of a class to access the static members of that class , therefore static Modified members are also called class variables and class methods . Static variables are different from instance variables , Instance variables are always accessed through objects , Because their values vary from object to object .
Please see the following example : public class Demo {
static int i = 10; int j; Demo() { this.j = 20; } public static void main(String[] args) { System.out.println(" Class variables i=" + Demo.i); Demo obj = new Demo(); System.out.println(" Instance variables j=" + obj.j); }
} Running results : Class variables i=10 Instance variables j=20 static Memory allocation Static variables are classes , Does not belong to any independent object , So you can access static variables without creating an instance of the class . The reason for this is , Because the compiler only creates a copy of the static variable for the entire class , That is, only one memory space is allocated , Although there are several examples , But these instances share that memory . Instance variables are different , Every time an object is created , Will allocate memory space once , The memory of different variables is independent of each other , They don't influence each other , change a The instance variable of the object does not affect b object .
Look at the code below : public class Demo {
static int i; int j; public static void main(String[] args) { Demo obj1 = new Demo(); obj1.i = 10; obj1.j = 20; Demo obj2 = new Demo(); System.out.println("obj1.i=" + obj1.i + ", obj1.j=" + obj1.j); System.out.println("obj2.i=" + obj2.i + ", obj2.j=" + obj2.j); }
} Running results : obj1.i=10, obj1.j=20 obj2.i=10, obj2.j=0
Be careful : Although static variables can also be accessed through objects , But not advocated , The compiler also generates warnings .
In the above code ,i It's a static variable , adopt obj1 change i Value , Will affect obj2;j Is instance variable , adopt obj1 change j Value , It won't affect obj2. This is because obj1.i and obj2.i Point to the same memory space , and obj1.j and obj2.j Point to different memory spaces , Please look at the chart below. :
chart 1 Static variable memory allocation
Be careful :static The variable is initialized when the class is loaded . in other words , As long as the class is loaded , Whether you use this or not static Variable , It will be initialized .
Summary : Class variables (class variables) With keywords static modification , When the class is loaded , Allocate memory for class variables , When regenerating an instance object of a class later , Will share this memory ( Class variables ), Modification of class variables by any object , Will affect other objects . There are two ways to access the outside : Access by object or by class name . Static methods A static method is a method that cannot operate on an object . for example ,Math Class pow() A method is a static method , The grammar is Math.pow(x, a), To calculate x Of a The next power , There is no need to create any Math object .
Because static methods cannot manipulate objects , So you can't access instance variables in static methods , You can only access static variables of your own class .
Static methods can be used in the following cases : A method doesn't need to access object state , The required parameters are provided by explicit parameters ( for example Math.pow()). A method only needs to access the static variables of the class .
Readers must have noticed ,main() It's also a static method , Do not operate on any object . actually , There are no objects when the program starts ,main() The way to do this is through the program portal , Will be executed and create the objects required by the program .
A summary of static variables and static methods : Static methods of a class can only access static variables ; Static methods of a class cannot directly call non static methods ; If access control permission allows , Static variables and static methods can also be accessed through objects , But not recommended ; There is no current object in the static method , So you can't use this, Of course, you can't use super; Static methods cannot be overridden by non static methods ; Constructor is not allowed to be declared as static Of ; Local variables cannot be used static modification .
Examples of static methods : public class Demo {
static int sum(int x, int y){ return x + y; } public static void main(String[] args) { int sum = Demo.sum(10, 10); System.out.println("10+10=" + sum); }
} Running results : 10+10=20
static Method is called without any instance of the class to which it belongs , So there is no this value , Cannot access instance variables , Otherwise, it will cause compilation error .
Be careful : Instance variables can only be accessed through objects , Cannot be accessed through class . Static initializer ( A static block ) A block is a piece of code surrounded by braces . Static initializer (Static Initializer) Is a class that exists in 、 Static block outside method . Static initializers are only used when the class is loaded ( The first time you use a class ) Do it once , Often used to initialize static variables .
Sample code : public class Demo {
public static int i; static{ i = 10; System.out.println("Now in static block."); } public void test() { System.out.println("test method: i=" + i); } public static void main(String[] args) { System.out.println("Demo.i=" + Demo.i); new Demo().test(); }
} The result of the operation is : Now in static block. Demo.i=10 test method: i=10 Static import Static import is Java 5 New features , Static variables and static methods used to import classes .
Generally, we import classes in this way : import packageName.className; // Import a specific class or import packageName.*; // Import all classes in the package
Static import can be written like this : import static packageName.className.methonName; // Import a specific static method or import static packageName.className.*; // Import all static members in the class
After import , You can call static methods directly with the method name in the current class , No more className.methodName To visit .
For frequently used static variables and static methods , You can import it statically . The advantage of static import is that it can simplify some operations , For example, output statements System.out.println(); Medium out Namely System Static variable of class , Can pass import static java.lang.System.*; Import it into , Next time call directly out.println() That's all right. .
Look at the code below : import static java.lang.System.*; import static java.lang.Math.random; public class Demo {
public static void main(String[] args) { out.println(" A random number generated :" + random()); }
} Running results : A random number generated :0.05800891549018705static Modifiers can be associated with variables 、 Methods used together , Said is “ static state ” Of .
Static variables and static methods can be accessed through class names , There is no need to create an object of a class to access the static members of that class , therefore static Modified members are also called class variables and class methods . Static variables are different from instance variables , Instance variables are always accessed through objects , Because their values vary from object to object .
Please see the following example : public class Demo {
static int i = 10; int j; Demo() { this.j = 20; } public static void main(String[] args) { System.out.println(" Class variables i=" + Demo.i); Demo obj = new Demo(); System.out.println(" Instance variables j=" + obj.j); }
} Running results : Class variables i=10 Instance variables j=20 static Memory allocation Static variables are classes , Does not belong to any independent object , So you can access static variables without creating an instance of the class . The reason for this is , Because the compiler only creates a copy of the static variable for the entire class , That is, only one memory space is allocated , Although there are several examples , But these instances share that memory . Instance variables are different , Every time an object is created , Will allocate memory space once , The memory of different variables is independent of each other , They don't influence each other , change a The instance variable of the object does not affect b object .
Look at the code below : public class Demo {
static int i; int j; public static void main(String[] args) { Demo obj1 = new Demo(); obj1.i = 10; obj1.j = 20; Demo obj2 = new Demo(); System.out.println("obj1.i=" + obj1.i + ", obj1.j=" + obj1.j); System.out.println("obj2.i=" + obj2.i + ", obj2.j=" + obj2.j); }
} Running results : obj1.i=10, obj1.j=20 obj2.i=10, obj2.j=0
Be careful : Although static variables can also be accessed through objects , But not advocated , The compiler also generates warnings .
In the above code ,i It's a static variable , adopt obj1 change i Value , Will affect obj2;j Is instance variable , adopt obj1 change j Value , It won't affect obj2. This is because obj1.i and obj2.i Point to the same memory space , and obj1.j and obj2.j Point to different memory spaces , Please look at the chart below. :
chart 1 Static variable memory allocation
Be careful :static The variable is initialized when the class is loaded . in other words , As long as the class is loaded , Whether you use this or not static Variable , It will be initialized .
Summary : Class variables (class variables) With keywords static modification , When the class is loaded , Allocate memory for class variables , When regenerating an instance object of a class later , Will share this memory ( Class variables ), Modification of class variables by any object , Will affect other objects . There are two ways to access the outside : Access by object or by class name . Static methods A static method is a method that cannot operate on an object . for example ,Math Class pow() A method is a static method , The grammar is Math.pow(x, a), To calculate x Of a The next power , There is no need to create any Math object .
Because static methods cannot manipulate objects , So you can't access instance variables in static methods , You can only access static variables of your own class .
Static methods can be used in the following cases : A method doesn't need to access object state , The required parameters are provided by explicit parameters ( for example Math.pow()). A method only needs to access the static variables of the class .
Readers must have noticed ,main() It's also a static method , Do not operate on any object . actually , There are no objects when the program starts ,main() The way to do this is through the program portal , Will be executed and create the objects required by the program .
A summary of static variables and static methods : Static methods of a class can only access static variables ; Static methods of a class cannot directly call non static methods ; If access control permission allows , Static variables and static methods can also be accessed through objects , But not recommended ; There is no current object in the static method , So you can't use this, Of course, you can't use super; Static methods cannot be overridden by non static methods ; Constructor is not allowed to be declared as static Of ; Local variables cannot be used static modification .
Examples of static methods : public class Demo {
static int sum(int x, int y){ return x + y; } public static void main(String[] args) { int sum = Demo.sum(10, 10); System.out.println("10+10=" + sum); }
} Running results : 10+10=20
static Method is called without any instance of the class to which it belongs , So there is no this value , Cannot access instance variables , Otherwise, it will cause compilation error .
Be careful : Instance variables can only be accessed through objects , Cannot be accessed through class . Static initializer ( A static block ) A block is a piece of code surrounded by braces . Static initializer (Static Initializer) Is a class that exists in 、 Static block outside method . Static initializers are only used when the class is loaded ( The first time you use a class ) Do it once , Often used to initialize static variables .
Sample code : public class Demo {
public static int i; static{ i = 10; System.out.println("Now in static block."); } public void test() { System.out.println("test method: i=" + i); } public static void main(String[] args) { System.out.println("Demo.i=" + Demo.i); new Demo().test(); }
} The result of the operation is : Now in static block. Demo.i=10 test method: i=10 Static import Static import is Java 5 New features , Static variables and static methods used to import classes .
Generally, we import classes in this way : import packageName.className; // Import a specific class or import packageName.*; // Import all classes in the package
Static import can be written like this : import static packageName.className.methonName; // Import a specific static method or import static packageName.className.*; // Import all static members in the class
After import , You can call static methods directly with the method name in the current class , No more className.methodName To visit .
For frequently used static variables and static methods , You can import it statically . The advantage of static import is that it can simplify some operations , For example, output statements System.out.println(); Medium out Namely System Static variable of class , Can pass import static java.lang.System.*; Import it into , Next time call directly out.println() That's all right. .
Look at the code below : import static java.lang.System.*; import static java.lang.Math.random; public class Demo {
public static void main(String[] args) { out.println(" A random number generated :" + random()); }
} Running results : A random number generated :0.05800891549018705
This article altogether 2612 Number of words , Average reading time ≈ 7 minute
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .