Summary of the static keyword

Forwarded From: https: //www.cnblogs.com/xrq730/p/4820992.html

 

Foreword

Before the final keyword talked about the role of one of the two questions I will ask job seekers every interview, another problem is that the text is written to the static. final and static, it is a small problem a person can see whether a solid foundation, and whether there are usually inquiring mind.

 

Static variables and static methods

The most basic use of the static keyword is:

1, was modified static variables that belong to class variables, by class name variable name referenced directly without the need for a new class

2, the modified static method belong to the class methods, by method name class name referenced directly, without the need for a new class

Modified static variables, static methods modified unified belong to the class of static resources are shared between instances of the class, in other words, a change, always change . JDK different static resources in the different classes and not all static resources into a single class, many people may assume that you want to do, of course, but ever thought why do it? Personally I think that there are three main benefits:

1, different classes have their own static resources, which can achieve a static resource classification. Such as mathematics and related resources on java.lang.Math static, the static resources and calendars related to java.util.Calendar in place, so it is clear

2, to avoid duplicate names. There are different class static variable names the same name, the name of the static method is normal, if all are in one inevitable problem with the name is repeated, this time how to do? Category placed just fine.

3, to avoid static resource unlimited expansion, which is well understood.

OK, and then a little bit further, but also some people confusing a problem: non-static method can reference static resources? Inside static methods can not reference static resources? Non-static method which can not reference static resources? Take for example this code, for example, if there is wrong?

Copy the code
1 public class A
2 {
3     private int i = 1;
4     
5     public static void main(String[] args)
6     {
7         i = 1;
8     }
9 }
Copy the code

Of course there is wrong, the place in line 7. So you may wish to ponder this question:

Static resources belong to the class, but is independent of the existence of the class. From the perspective of class loading mechanism of the JVM, the static initialization of the resource class is loaded, rather than static resource is a new type of load time . Initialize the class early in the new category, such as Class.forName ( "xxx") method is to initialize a class, but it is not new, just load a static resource of this class fills. So for static resources, it is impossible to know what a non-static resource category there are; but for the non-static resources is not the case, because it is generated after the new came out, so these things belong to the class of it You can know. So few answers to the above questions is very clear:

1, static methods can not reference the non-static resources? No, something new will be produced when, after initialization for static resources exist, it did not know it.

2, static methods which can not reference static resources? Yes, because classes are initialized when loaded, we all know each other.

3, non-static methods which can not reference static resources? Yes, non-static method is an instance method, it is only produced after the new, then the content of which belong to the class know.

 

Static block

Static block is one of the important applications of static. When a class is used to initialize the exercise effect, and static variables, static methods, as a static block code which is executed only once, and only perform class initialization time . Static blocks is very simple, to mention but three small details:

Copy the code
 1 public class A
 2 {
 3     private static int a = B();
 4     
 5     static
 6     {
 7         System.out.println("Enter A.static block");
 8     }
 9     
10     public static void main(String[] args)
11     {
12         new A();
13     }
14     
15     public static int B()
16     {
17         System.out.println("Enter A.B()");
18         return 1;
19     }
20 }
Copy the code

Print result:

Enter A.B()
Enter A.static block

First conclusion: the load order of static resources is defined strictly in accordance with the order to load the static resources . This and Zhou Zhiming teacher "in-depth understanding of the Java Virtual Machine: JVM advanced features and best practices" in the class initialization argument " <the clinit> () method is assigned automatically by the compiler collection action class in all classes and static variables in a block of statements (static {} block) statements merger sequentially compiler is collected in order of appearance in the source file by the statements of the decision "is consistent.

Look at an example:

Copy the code
 1 public class A
 2 {
 3     static
 4     {
 5         c = 3;
 6         System.out.println(c);
 7     }
 8     
 9     private static int c;
10 }
Copy the code

Line 6 of this code is wrong "Can not reference a field before it is defined". The second conclusion drawn from this example: static block of code is defined for the static variable after it, can be assigned, but can not be accessed .

One final example:

Copy the code
 1 public class A
 2 {
 3     static
 4     {
 5         System.out.println("A.static block");
 6     }
 7     
 8     public A()
 9     {
10         System.out.println("A.constructor()");
11     }
12 }
Copy the code
Copy the code
 1 public class B extends A
 2 {
 3     static 
 4     {
 5         System.out.println("B.static block");
 6     }
 7     
 8     public B()
 9     {
10         System.out.println("B.constructor()");
11     }
12     
13     public static void main(String[] args)
14     {
15         new B();
16         new B();
17     }
18 }
Copy the code

The result is

A.static block
B.static block
A.constructor()
B.constructor()
A.constructor()
B.constructor()

The third conclusion drawn example: static block of code is strictly in accordance with the parent class static block of code -> sub-class static code blocks loaded and loaded only once .

 

static modification class

This use relatively less than the previous usage, and it is under normal circumstances is not modified static class, if you want to modify a static class, indicating that this class is a static inner class (note that only modifies a static inner classes), that is anonymous inner classes. Like four kinds rejection mechanism in the thread pool ThreadPoolExecutor CallerRunsPolicy, AbortPolicy, DiscardPolicy, DiscardOldestPolicy is static inner classes. Static inner classes relevant content will be specifically mentioned when writing to the internal classes.

 

import static

The more popular, basic little place with a saw, use JUnit might use, write assert time will be convenient. import static is a new feature after JDK1.5, both keywords can be used in conjunction with a designated import the specified static resource class, and does not require the use of the class name. resource name, resource name can be used directly. Note, Import static must be so written, but can not be written static import. For example look at:

Copy the code
1 import static java.lang.Math.*;
2 
3 public class A
4 {
5     public static void main(String[] args)
6     {
7         System.out.println(sin(2.2));
8     }
9 }
Copy the code

So write means I imported all the static resources in Math, main function which I can directly use sin (2.2) without the use of Math.sin (2.2) a. Note, write Import static java.lang.Math. * , The last. "*" Is a must, with these two characters is the only means to import all the static resources under Math, written import static java.lang. Math is problematic. Of course, we can also specify to import only a static resource, such as import only sin Math under this method instead of importing all the static resources in Math:

Copy the code
1 import static java.lang.Math.sin;
2 
3 public class A
4 {
5     public static void main(String[] args)
6     {
7         System.out.println(sin(2.2));
8     }
9 }
Copy the code

So write is not the problem. Import static variables, too, are interested can try their own. For import static, personal attitude is:

1, simplifies some operations, such as static imports all static resources in Math, where the frequent use of the Math class under static resources can be a lot less "Math."

2, reduces the readability of the code

Import recommended in some scenarios specific static resources, not recommended. "*" Import mode.

==================================================================================


Every place I can not guarantee write is right, but at least promise not to copy, paste does not ensure that every word, every line of code after careful scrutiny and careful consideration. Behind every article, I hope to be able to see their skills, attitudes to life.

I believe that Steve Jobs said, only those who are crazy enough to think they can change the world can truly change the world. The face of pressure, I can burn the midnight oil, around the clock; the face of difficulties, I am willing to grasp the nettle, never back down.

In fact, I want to say is, I'm just a programmer, this is purely my whole life now.

================================================== ===========================

Foreword

Before the final keyword talked about the role of one of the two questions I will ask job seekers every interview, another problem is that the text is written to the static. final and static, it is a small problem a person can see whether a solid foundation, and whether there are usually inquiring mind.

 

Static variables and static methods

The most basic use of the static keyword is:

1, was modified static variables that belong to class variables, by class name variable name referenced directly without the need for a new class

2, the modified static method belong to the class methods, by method name class name referenced directly, without the need for a new class

Modified static variables, static methods modified unified belong to the class of static resources are shared between instances of the class, in other words, a change, always change . JDK different static resources in the different classes and not all static resources into a single class, many people may assume that you want to do, of course, but ever thought why do it? Personally I think that there are three main benefits:

1, different classes have their own static resources, which can achieve a static resource classification. Such as mathematics and related resources on java.lang.Math static, the static resources and calendars related to java.util.Calendar in place, so it is clear

2, to avoid duplicate names. There are different class static variable names the same name, the name of the static method is normal, if all are in one inevitable problem with the name is repeated, this time how to do? Category placed just fine.

3, to avoid static resource unlimited expansion, which is well understood.

OK, and then a little bit further, but also some people confusing a problem: non-static method can reference static resources? Inside static methods can not reference static resources? Non-static method which can not reference static resources? Take for example this code, for example, if there is wrong?

Copy the code
1 public class A
2 {
3     private int i = 1;
4     
5     public static void main(String[] args)
6     {
7         i = 1;
8     }
9 }
Copy the code

Of course there is wrong, the place in line 7. So you may wish to ponder this question:

Static resources belong to the class, but is independent of the existence of the class. From the perspective of class loading mechanism of the JVM, the static initialization of the resource class is loaded, rather than static resource is a new type of load time . Initialize the class early in the new category, such as Class.forName ( "xxx") method is to initialize a class, but it is not new, just load a static resource of this class fills. So for static resources, it is impossible to know what a non-static resource category there are; but for the non-static resources is not the case, because it is generated after the new came out, so these things belong to the class of it You can know. So few answers to the above questions is very clear:

1, static methods can not reference the non-static resources? No, something new will be produced when, after initialization for static resources exist, it did not know it.

2, static methods which can not reference static resources? Yes, because classes are initialized when loaded, we all know each other.

3, non-static methods which can not reference static resources? Yes, non-static method is an instance method, it is only produced after the new, then the content of which belong to the class know.

 

Static block

Static block is one of the important applications of static. When a class is used to initialize the exercise effect, and static variables, static methods, as a static block code which is executed only once, and only perform class initialization time . Static blocks is very simple, to mention but three small details:

Copy the code
 1 public class A
 2 {
 3     private static int a = B();
 4     
 5     static
 6     {
 7         System.out.println("Enter A.static block");
 8     }
 9     
10     public static void main(String[] args)
11     {
12         new A();
13     }
14     
15     public static int B()
16     {
17         System.out.println("Enter A.B()");
18         return 1;
19     }
20 }
Copy the code

Print result:

Enter A.B()
Enter A.static block

First conclusion: the load order of static resources is defined strictly in accordance with the order to load the static resources . This and Zhou Zhiming teacher "in-depth understanding of the Java Virtual Machine: JVM advanced features and best practices" in the class initialization argument " <the clinit> () method is assigned automatically by the compiler collection action class in all classes and static variables in a block of statements (static {} block) statements merger sequentially compiler is collected in order of appearance in the source file by the statements of the decision "is consistent.

Look at an example:

Copy the code
 1 public class A
 2 {
 3     static
 4     {
 5         c = 3;
 6         System.out.println(c);
 7     }
 8     
 9     private static int c;
10 }
Copy the code

Line 6 of this code is wrong "Can not reference a field before it is defined". The second conclusion drawn from this example: static block of code is defined for the static variable after it, can be assigned, but can not be accessed .

One final example:

Copy the code
 1 public class A
 2 {
 3     static
 4     {
 5         System.out.println("A.static block");
 6     }
 7     
 8     public A()
 9     {
10         System.out.println("A.constructor()");
11     }
12 }
Copy the code
Copy the code
 1 public class B extends A
 2 {
 3     static 
 4     {
 5         System.out.println("B.static block");
 6     }
 7     
 8     public B()
 9     {
10         System.out.println("B.constructor()");
11     }
12     
13     public static void main(String[] args)
14     {
15         new B();
16         new B();
17     }
18 }
Copy the code

The result is

A.static block
B.static block
A.constructor()
B.constructor()
A.constructor()
B.constructor()

The third conclusion drawn example: static block of code is strictly in accordance with the parent class static block of code -> sub-class static code blocks loaded and loaded only once .

 

static modification class

This use relatively less than the previous usage, and it is under normal circumstances is not modified static class, if you want to modify a static class, indicating that this class is a static inner class (note that only modifies a static inner classes), that is anonymous inner classes. Like four kinds rejection mechanism in the thread pool ThreadPoolExecutor CallerRunsPolicy, AbortPolicy, DiscardPolicy, DiscardOldestPolicy is static inner classes. Static inner classes relevant content will be specifically mentioned when writing to the internal classes.

 

import static

The more popular, basic little place with a saw, use JUnit might use, write assert time will be convenient. import static is a new feature after JDK1.5, both keywords can be used in conjunction with a designated import the specified static resource class, and does not require the use of the class name. resource name, resource name can be used directly. Note, Import static must be so written, but can not be written static import. For example look at:

Copy the code
1 import static java.lang.Math.*;
2 
3 public class A
4 {
5     public static void main(String[] args)
6     {
7         System.out.println(sin(2.2));
8     }
9 }
Copy the code

So write means I imported all the static resources in Math, main function which I can directly use sin (2.2) without the use of Math.sin (2.2) a. Note, write Import static java.lang.Math. * , The last. "*" Is a must, with these two characters is the only means to import all the static resources under Math, written import static java.lang. Math is problematic. Of course, we can also specify to import only a static resource, such as import only sin Math under this method instead of importing all the static resources in Math:

Copy the code
1 import static java.lang.Math.sin;
2 
3 public class A
4 {
5     public static void main(String[] args)
6     {
7         System.out.println(sin(2.2));
8     }
9 }
Copy the code

So write is not the problem. Import static variables, too, are interested can try their own. For import static, personal attitude is:

1, simplifies some operations, such as static imports all static resources in Math, where the frequent use of the Math class under static resources can be a lot less "Math."

2, reduces the readability of the code

Import recommended in some scenarios specific static resources, not recommended. "*" Import mode.

Guess you like

Origin www.cnblogs.com/fxwoniu/p/12000693.html