"Reprint" Static keyword parsing in Java
The static keyword is a hard-to-understand keyword that many friends encounter when writing code and reading code, and is one of the points of knowledge that interviewers in major companies like to ask during an interview. The following is a discussion of the use of the static keyword and the usual easy to misunderstand the place, and finally listed some of the interview written in the common questions about static. The following is the directory outline for this article:
I. Purpose of the STATIC keyword
Two. The error of the static keyword
Three. Common written test questions
If there are any shortcomings, I hope to understand and welcome the criticism.
Please respect the author's labor results, reproduced please indicate the original link: http://www.cnblogs.com/dolphin0520/p/3799052.html
I. Purpose of the STATIC keyword
In the Java programming thought P86 page, there is a passage:
Thestatic method is the method without this. A non-static method cannot be called inside a static method, which in turn is possible. It is also possible to invoke the static method only through the class itself, without creating any objects. This is actually the primary use of the static method . ”
While this remark only illustrates the special character of the static method, it is possible to see the basic role of the static keyword, in short, one sentence to describe:
Makes it easy to invoke (method/variable) without creating an object.
Obviously, a method or variable modified by the static keyword does not have to rely on an object for access, as long as the class is loaded, it can be accessed through the class name.
Static can be used to modify member methods of a class, member variables of a class, and you can write static code blocks to optimize program performance.
1) static method
Static methods are commonly referred to as static methods, and because they can be accessed without relying on any object, there is no this for static methods because it is not attached to any object, and since there are no objects, this is not the case. And because of this feature, non-static member variables and non-static member methods of the class cannot be accessed in a static method, because non-static member methods/variables must be dependent on a specific object to be able to be called.
It is important to note, though, that non-static member methods and non-static member variables cannot be accessed in static methods, but static member methods/variables are accessible in non-static member methods. To give a simple example:
In the above code, because the Print2 method is independent of the object, it can be called directly with the class name. If you can access a non-static method/variable in a static method, then if you have the following statement in the Main method:
Myobject.print2 ();
At this time the object is not, STR2 does not exist at all, so there will be contradictions. The same is true for methods, because you cannot predict whether non-static member variables are accessed in the Print1 method, and you also prohibit access to non-static member methods in static member methods.
For non-static member methods, it is clear that there is no limit to accessing static member methods/variables.
Therefore, if you want to call a method without creating an object, you can set this method to static. Our most common static method is the main method, and as for why the main method must be static, it is now clear. Because the program does not create any objects when it executes the main method, it is only accessible through the class name.
Also remember that the constructor of a class is actually a static method even if it is not declared as static.
2) Static variable
Static variables are also known as static variables, except that the static variables are shared by all objects, only one copy in memory, and are initialized only when the class is first loaded. Instead of static variables, which are owned by an object, are initialized when the object is created, there are multiple copies, and the replicas owned by each object do not affect each other.
The initialization order of static member variables is initialized in the order in which they are defined.
3) Static code block
Another key function of the static keyword is to form static blocks of code to optimize program performance. A static block can be placed anywhere in the class and can have more than one static block in the class. When the class is first loaded, each static block is executed in the order of the static blocks and is executed only once.
Why static blocks can be used to optimize the performance of a program because of its nature: it executes only once when the class is loaded. Let's look at an example:
Class person{ private Date birthDate; Public person (Date birthDate) { this.birthdate = birthDate; } Boolean Isbornboomer () { Date startdate = date.valueof ("1946"); Date endDate = date.valueof ("1964"); Return Birthdate.compareto (startdate) >=0 && Birthdate.compareto (endDate) < 0;} }
Isbornboomer is used for this person is born 1946-1964, and each time Isbornboomer is called, will generate StartDate and birthdate two objects, resulting in space waste, if changed to such efficiency will be better:
Class person{ private Date birthDate; private static Date startdate,enddate; static{ startdate = date.valueof ("1946"); EndDate = date.valueof ("1964"); } Public person (Date birthDate) { this.birthdate = birthDate; } Boolean Isbornboomer () { return Birthdate.compareto (startdate) >=0 && Birthdate.compareto (endDate) < 0; }}
As a result, some initialization operations that only need to be performed once are placed in a static block of code.
Two. The error of the static keyword
Does the 1.static keyword change the access rights of members in a class?
Some beginner friends confuse the static in Java with the function of the static keyword in C + +. Here's just one thing to keep in mind: unlike static in C + +, the static keyword in Java does not affect the scope of a variable or method. The only private, public, protected (including package access rights) keywords that can affect access in Java. See the following example to understand:
The error "Person.age is not seen" indicates that the STATIC keyword does not alter the access rights of variables and methods.
2. Can I access static member variables through this?
Although there is no this for static methods, is it possible to access static member variables through this in a non-static method? Let's look at one of the following examples, what is the result of this code output?
public class main{ static int value =; public static void Main (string[] args) throws exception{ new Main (). Printvalue (); private void Printvalue () { int value = 3; System.out.println (This.value); }}
Output:33
This is the understanding of the main expedition this and the static. What does this represent? This represents the current object, so the current object is the object generated through new main () by calling Printvalue with new Main (). The static variable is enjoyed by the object, so the value of This.value in Printvalue is undoubtedly 33. The value inside the Printvalue method is a local variable and cannot be associated with this at all, so the output is 33. Always keep in mind that static member variables, while independent of the object, do not mean that they cannot be accessed through objects, and that all static and static variables can be accessed through the object (as long as access is sufficient).
Can 3.static act on local variables?
Static is a scoped local variable in C + +, but in Java it is important to remember that static is not allowed to decorate local variables. Do not ask why, this is the Java syntax of the provisions.
Three. Common written test questions
The following are some of the interview written in the frequently encountered on the static keyword of the topic, for reference only, if there are additional welcome comments below.
1. What is the output of the following code?
public class Test extends base{ static{ System.out.println ("Test static"); } Public Test () { System.out.println ("Test constructor"); } public static void Main (string[] args) { new Test ();} } Class base{ static{ System.out.println ("Base static"); } Public Base () { System.out.println ("base constructor");} }
Output
Base static
Test static
Base constructor
Test constructor
As to why this is the result, we do not discuss, first of all, to think about this code specific execution process, at the beginning of execution, the first to find the main method, because the main method is the entry of the program, but before executing the main method, you must first load the test class, When loading the test class, it is found that the test class inherits from the base class, so it will go first to load the base class, and when the base class is loaded, the static block is executed. After the base class is loaded, the test class continues to load, and then the static block is executed when the test class is found with a static block. After the required classes have been loaded, the main method is executed. When you execute new Test () in the main method, the constructor of the parent class is called first, and then the constructor for itself is called. As a result, the above output appears.
2. What is the output of this piece of code?
package Com.pachra.a;public class C {person person = new Person ("Test"); static { SYSTEM.OUT.PRINTLN ("Test Static");} Public C () {System.out.println ("test constructor");} public static void Main (string[] args) {new MyClass ();}} /* * 1. Look for the main function, load C, and find the static block print test static * 2. Executes the main function, loads the MyClass, and its inheritance c,c is loaded, so the static block print MyClass static is executed, loading is complete * 3. Initializes the MyClass object, which inherits the C, and initializes the member variable of C, the constructor method, that is: Initialize person, execute constructor c;print person static, person test, test constructor * 4. Initializes the MyClass member variable, the constructor method, that is: Print person MyClass, MyClass constructor */class person {static {System.out.println (' person Static ");} Public person (String str) {System.out.println (' person ' + str);}} Class MyClass extends C {person person = new Person ("MyClass"), Static {System.out.println ("MyClass Static");} Public MyClass () {System.out.println ("MyClass constructor");}} /* Output: * Test static * MyClass static * person static * Person Test * Test constructor * Person MyClass * MyClass Co Nstructor */
Similarly, let's consider the specific implementation of this code. The test class is loaded first, so the static blocks in the test class are executed. Then the new MyClass () is executed, and the MyClass class is not loaded, so the MyClass class needs to be loaded. When loading the MyClass class, it is found that the MyClass class inherits from the test class, but because the test class has already been loaded, only the MyClass class needs to be loaded, then the static blocks in the MyClass class are executed. After loading, the object is generated from the constructor. When generating an object, the member variable of the parent class must be initialized, so the person person in test = new person () is executed, and the person class is not loaded, so the person class is loaded first and the static block in the person class is executed. Then executes the constructor of the parent class, completes the initialization of the parent class, and then initializes itself, then executes the person person in MyClass = new person () and finally executes the MyClass constructor.
3. What is the output of this piece of code?
public class Test { static{ System.out.println ("Test static 1"); public static void Main (string[] args) { } static{ System.out.println ("Test static 2");} } /* Output: * Test static 1 * Test static 2 */
Although there is no statement in the main method, it is still output, as explained above. In addition, the static block can appear anywhere in the class (as long as it is not inside the method, remember that no method is internal), and execution is performed in the order of the static blocks.
Resources:
http://lavasoft.blog.51cto.com/62575/18771/
Http://www.51cto.com/specbook/24/35011.htm
http://blog.csdn.net/zhu_apollo/article/details/1888219
Http://blog.sina.com.cn/s/blog_70b845780100n9zz.html
http://hi.baidu.com/yuiezt/item/b71ff5fbfe9c385cc8f3370d
http://bbs.csdn.net/topics/330251070
http://yezixingchen.iteye.com/blog/1597186
The idea of Java programming
Static keyword parsing in Java, "Reprint-java Foundation"