Java static keyword

await 2021-09-15 07:19:34
java static keyword


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 .

版权声明
本文为[await]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909125824186S.html

  1. 别再说你不会JVM性能监控和调优了,2021华为Java高级面试题及答案,
  2. 15 useful cron work examples commonly used by Senior Linux system administrators
  3. Ne dites pas que vous ne pouvez pas surveiller et ajuster les performances JVM, 2021 Huawei Java Advanced interview Questions and Answers,
  4. 別再說你不會JVM性能監控和調優了,2021華為Java高級面試題及答案,
  5. 十多家大厂Java面试真题锦集干货整理,Java开发者该学习哪些东西提高竞争力?
  6. 十分钟带你回顾Spring常问的知识点,35岁老年程序员的绝地翻身之路,
  7. 区区一个SpringBoot问题就被干趴下了,看完这一篇就够了!
  8. K8s gestion des ressources (opérations de base)
  9. Java and cloud native dating
  10. 區區一個SpringBoot問題就被幹趴下了,看完這一篇就够了!
  11. Un problème de démarrage de printemps dans le district a été séché, et c'est assez!
  12. Dix minutes pour vous faire passer en revue les points de connaissance que Spring demande souvent, le chemin du retour Jedi d'un programmeur âgé de 35 ans,
  13. Plus d'une douzaine de grandes usines Java interview vrai sujet brocade collection de marchandises sèches, les développeurs Java devraient apprendre ce qui améliore la compétitivité?
  14. 十分鐘帶你回顧Spring常問的知識點,35歲老年程序員的絕地翻身之路,
  15. Guide de route d'apprentissage Java, redis a plusieurs types de données?
  16. 华为Java高级工程师面试题,字节跳动上千道精选面试题还不刷起来!
  17. 华为Java面试题目,腾讯Java开发面试记录,
  18. Propriétés et méthodes des objets Array en javascript!,Pseudo - classes et pseudo - éléments pour CSS
  19. Design pattern -- agent pattern
  20. 華為Java面試題目,騰訊Java開發面試記錄,
  21. Huawei Java interview title, Tencent Java Development interview record,
  22. Huawei Java Senior Engineer interview question, Byte Jumping thousand Selected Interview Question is still not Brushed!
  23. 双非本科字节跳动Java面试题分享,一篇文章教你搞定计算机网络面试,
  24. 又到一年金三银四,2021最新Java笔试题及答案,
  25. Huawei Finance and Economics 2021 Spring Recruitment interview, what is distributed Lock?Pourquoi utiliser des serrures distribuées?
  26. Un an plus tard, Golden, Silver, Silver, and Silver, 2021, the latest Java written Examination Questions and Answers,
  27. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  28. Computer graduation project java online voting system based on SSM
  29. K8s gestion des ressources (opérations de base)
  30. 又到一年金三銀四,2021最新Java筆試題及答案,
  31. Collection de code de base JavaScript (1)
  32. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  33. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  34. Cloud Security Daily 210914: Red Hat Jboss Middleware Platform found important Security Vulnerability and needs to be upgraded as soon as possible
  35. 吐血整理,腾讯团队实力打造spring入门教程,
  36. 史上最全的微服务专业术语面试50问,字节跳动Java岗经典面试真题,
  37. Absolument!C'est l'analyse la plus détaillée du code source de hashtap que j'ai jamais vu!
  38. Computer graduation project Java logistics order management system of logistics company based on SSM
  39. Talk about Kafka: source code analysis of producer
  40. [springboot2 starts from 0] development tips - Lombok, devtools, spring initailizr
  41. 国内一线互联网公司面试题汇总,2021年大厂Java岗面试必问,
  42. 啃完吃透保你涨薪5K,熬夜整理小米Java面试题,
  43. 和字节跳动大佬的技术面谈,Redis成神之路电子版教程已问世,
  44. Le terme professionnel le plus complet de l'histoire des micro - services interview 50 questions, Byte Jumping Java post Classic interview vrai problème,
  45. After using mybatisplus, I haven't written SQL for a long time
  46. [springboot2 starts from 0] how to write a springboot application?
  47. Huawei cloud guassdb (for redis) released a new version, and the two core features were officially unveiled
  48. 和字節跳動大佬的技術面談,Redis成神之路電子版教程已問世,
  49. 啃完吃透保你漲薪5K,熬夜整理小米Java面試題,
  50. Avec l'interview technique du gigolo, le tutoriel électronique redis est sorti.
  51. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  52. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  53. Le tri des crachats de sang, la force de l'équipe Tencent pour créer le tutoriel d'introduction au printemps,
  54. Java and scala concurrency Fundamentals
  55. Analysis of java thread source code based on Hotspot
  56. 國內一線互聯網公司面試題匯總,2021年大廠Java崗面試必問,
  57. Introduction au module de contrôle de Connexion MySQL
  58. 大厂高级测试面试题,Java面试基础技能罗列,
  59. Comprendre l'architecture sous - jacente d'InnoDB en exécutant une instruction
  60. Chargeur de classe 1 Tomcat