Static keyword (ii) function summary

Source: Internet
Author: User

Static variables and static methods

The most basic usage of the Static keyword is:

1. Variables modified by static belong to class variables, which can be referenced directly by the name of the class, without the need for a new class to

2. The method that is modified by static is a class method, which can be referenced directly by the class name. Method name, without the need for a new class to

Static modified variables, statically modified methods, are common to the class of the constant resources, is shared between class instances, in other words, a change, everywhere change. The JDK puts different static resources in different classes without putting all the static resources in one class, and many people may assume that they certainly do, but have you ever wondered why you should do that? Personally, there are three main benefits:

1, different classes have their own static resources, which can achieve static resource classification. For example, mathematical-related static resources in the Java.lang.Math, and calendar-related static resources in the Java.util.Calendar, so it is clear

2, avoid duplicate names. It is also normal to have static variable names and static method names between different classes, and if all of them are put together, the inevitable problem is name duplication. It's OK to place the classification.

3, to avoid static resource class Unlimited expansion, this is very good understanding.

OK, and then slightly deeper, but also some people are easy to confuse a problem: static methods can not reference non-static resources? Static methods can be used to reference static resources? Can a static resource be referenced in a non-static method? For example, with this code as an example, is there a mistake?

1 public class A2 {3     private int i = 1;4     5 public     static void Main (string[] args) 6     {7         i = 1;8     }9}

Of course there is a mistake in the 7th line of the place. Think of it this way:

Static resources belong to classes, but are independent of the class existence. From the point of view of the class loading mechanism of the JVM, static resources are loaded when the class is initialized, and non-static resources are loaded when the class is new. The initialization of a class is earlier than the class's new, such as the Class.forName ("xxx") method, which initializes a class, but does not have new it, but simply loads the static resources of the class. Therefore, it is impossible for static resources to know what non-static resources are in a class, but it is not the same for non-static resources, because it is generated after new, so it can be known as a class of these things. So the answers to these questions are clear:

1. Can static methods reference non-static resources? No, new is the time to produce things, for the initialization of the existence of static resources, do not know it at all.

2, static methods inside can reference static resources? Yes, because they are all loaded at the time of class initialization, we all know each other.

3, non-static methods can reference static resources? Yes, a non-static method is an instance method, which is generated after new, so it is known as the content of the class.

Static block

Static blocks are also one of the important applications of static. Also used to initialize a class when the role of the exercise, and static variables, static methods, the code inside the static block is executed only once, and only in the initialization of the class execution. Static blocks are simple, but mention three small details:

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     public     static void Main (string[] args) One     {         new A ();     }14     static int B () +     {         System.out.println ("Enter a.b ()");         return 1;19     }20}

Printing results are

Enter A.B () Enter a.static block

The first conclusion is that the load order of static resources is loaded strictly according to the order of static resources ' definition. This and Zhou Zhiming teacher "in-depth understanding of Java Virtual machines: JVM advanced features and best practices" in class initialization "<clinit> () method is the compiler automatically collects all class variables in the class assignment action and Static statement block (static{} Block), the order in which the compiler collects the statements is consistent with the order in which the statements appear in the source file .

Let's look at an example:

1 public class A 2 {3     static 4     {5         c = 3; 6         System.out.println (c); 7     } 8      9     Private STA TIC int c;10}

The 6th line of this code is the error "cannot reference a field before it is defined". The second conclusion from this example is that a static block of code can be assigned to a static variable after it is defined, but it cannot be accessed.

One last small example:

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 ()");     }12}
   
1 public class B extends A 2 {3     static  4     {5         System.out.println ("b.static block"); 6     } 7      8< C19/>public B () 9     {         System.out.println ("B.constructor ()");}12 public     static void Main (string[] args) +     {         new B (); +         -new B ();     }18}

The result is

A.static blockb.static Blocka.constructor () b.constructor () A.constructor () B.constructor ()

This example concludes with a third conclusion: static code blocks are loaded strictly in the order of the subclass static code blocks, such as the parent static code block, and only once.

static modifier class

This is used relatively much less than the previous usage, static is generally not to modify the class, if static to decorate a class, the class is a static inner class (note that static can only decorate an inner class), that is, anonymous inner class. Like the four deny mechanisms in the thread pool Threadpoolexecutor callerrunspolicy, AbortPolicy, Discardpolicy, and Discardoldestpolicy are static inner classes. Static internal class-related content is specifically addressed when writing internal classes.

Import static

This is relatively unpopular, almost rarely see a place to use, using JUnit may be used, write the assert will be convenient. Import Static is a new feature after JDK1.5, which can be used in conjunction with the two keyword to specify that a specified static resource is imported into a class and does not require a class name. Resource name, you can use the resource name directly. Note that import static must be written so that it cannot be written as a static import. Take a look at the following example:

1 Import static JAVA.LANG.MATH.*;2 3 public class A4 {5 public     static void Main (string[] args) 6     {7         System.out. println (sin (2.2)); 8     }9}

This means that I have imported all the static resources under math, and I can use sin (2.2) directly in the main function without using Math.sin (2.2). Note that to write the import static java.lang.math.*, the last ". *" is not rare, with these two characters only means that all static resources under Math are imported and written as import static Java.lang.Math is problematic. Of course, we can also specify to import only a static resource, such as importing the math under sin instead of importing all the static resources under math:

1 Import static JAVA.LANG.MATH.SIN;2 3 public class A4 {5 public     static void Main (string[] args) 6     {7         System.ou T.println (sin (2.2)); 8     }9}

It's no problem to write like this. Importing static variables is also the same, interested can try it yourself. For import static, the personal attitude is:

1, simplifying some operations, such as static import of all static resources under math, in the frequent use of static resources under the math class, there can be a lot less "math."

2, reduce the readability of the Code

It is recommended that you import specific static resources under certain scenarios, and do not recommend the ". *" Import method.

Static keyword (ii) function summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.