The static keyword is a keyword that many friends encounter when writing and reading code. It is also one of the knowledge points that interviewers from major companies like to ask during interviews. Let’s first talk about the usage of static keywords and the common misunderstandings. Finally, we list some common test questions about static in the written interview. Here is the directory outline of this article:
1. The purpose of static keywords
2. Misconceptions of static keywords
3. Common written interview questions
If there is any incorrectness, I hope to understand and welcome criticism and correction.
Please respect the author's labor achievements. Please indicate the original link when reprinting:
http://www.cnblogs.com/dolphin0520/p/3799052.html
1. The purpose of static keywords
"The static method is a method without this. Non-static methods cannot be called inside the static method, which is in turn possible. And the static method can be called only through the class itself without creating any object. This is actually the main purpose of the static method."
Although this passage only illustrates the special features of the static method, it can be seen that the basic function of the static keyword. In short, it is described in one sentence:
It is convenient to call (method/variable) without creating an object.
Obviously, methods or variables modified by static keywords do not need to rely on objects for access. As long as the class is loaded, they can be accessed through the class name.
static can be used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance.
1) static method
The static method is generally called a static method. Since static methods can be accessed without relying on any object, there is no this for static methods because it does not depend on any object. Since there are no objects, there is no such thing as this. And due to this feature, non-static member variables and non-static member methods of the class cannot be accessed in static methods, because non-static member methods/variables must rely on specific objects to be called.
But it should be noted that although non-static member methods and non-static member variables cannot be accessed in static methods, static member methods/variables can be accessed in non-static member methods. Let's give a simple example:
In the above code, since the print2 method exists independently of the object, it can be called directly by class name. If non-static methods/variables can be accessed in static methods, then if there is the following statement in the main method:
MyObject.print2();
At this time, there is no object, and str2 does not exist at all, so there will be a contradiction. The same is true for methods. Since you cannot predict whether non-static member variables are accessed in print1 method, accessing non-static member methods in static member methods is also prohibited.
And for non-static member methods, it is obviously unlimited to access 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. As for why the main method must be static, it is very clear now. Because the program does not create any object when executing the main method, it can only be accessed through the class name.
Also remember that even if it is not displayed as static, the constructor of the class is actually a static method.
2) static variables
Static variables are also called static variables. The difference between static variables and non-static variables is that static variables are shared by all objects, with only one copy in memory, which will be initialized if and only when the class is loaded for the first time. Non-static variables are owned by objects and are initialized when creating objects. There are multiple copies, and the copies owned by each object do not affect each other.
The initialization order of static member variables is initialized in the defined order.
3) Static code block
Another key function of the static keyword is to form static code blocks to optimize program performance. The static block can be placed anywhere in the class, and there can be multiple static blocks in the class. When the class is first loaded, each static block will be executed in the order of static blocks and will only be executed once.
The reason why static blocks can be used to optimize program performance is because of its characteristic: they will only be executed once when the class is loaded. Here is 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 to whether this person was born in 1946-1964. Every time isBornBoomer is called, two objects will be generated, which will cause waste of space. If changed to this, it 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 && birthday.compareTo(endDate) < 0;}} Therefore, many times, some initialization operations that only need to be performed once will be placed in the static code block.
2. Misconceptions of static keywords
1. Will the static keyword change the access rights of members in the class?
Some beginners will confuse static in java with static keyword functions in C/C++. Just remember one thing here: unlike static in C/C++, the static keyword in Java will not affect the scope of variables or methods. In Java, the only keywords that can affect access permissions are private, public, and protected (including package access permissions). Look at the following examples to understand:
The prompt error "Person.age is not visible", which means that the static keyword does not change the access permissions of variables and methods.
2. Can static member variables be accessed through this?
Although there is no this for static methods, can static member variables be accessed through this in non-static methods? Let’s first look at the following example. What is the result of this code output?
public class Main { static int value = 33; public static void main(String[] args) throws Exception{new Main().printValue();}private void printValue(){int value = 3;System.out.println(this.value);}} 33
This is mainly the main observation team to understand this and static. What does this stand for? This represents the current object. If printValue is called through new Main(), the current object is the object generated by 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 remember one thing here: Although static member variables are independent of objects, they do not mean they cannot be accessed through objects. All static methods and static variables can be accessed through objects (as long as the access permissions are sufficient).
3. Can static act on local variables?
In C/C++, static can scope local variables, but remember in Java: static is not allowed to be used to modify local variables. Don't ask why, this is the provision of Java syntax.
3. Common written interview questions
The following lists some questions about static keywords that are often encountered in the written interview. They are for reference only. If you have any supplements, please feel free to leave a message below.
1. What is the output result 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");}} base static
test static
base constructor
test constructor
As for why this result is, let's not discuss it first. Let's think about the specific execution process of this code. At the beginning of execution, we must first find the main method, because the main method is the entrance to the program, but before executing the main method, the Test class must be loaded first. When loading the Test class, it is found that the Test class inherits from the Base class, so it will turn to load the Base class first. When loading the Base class, it finds that there is a static block, and then executes the static block. After the Base class is loaded, the Test class continues to load, and then finds that there are static blocks in the Test class, so the static block is executed. After loading the required class, the main method begins to be executed. When executing new Test() in the main method, the constructor of the parent class will be called first, and then the constructor of its own. Therefore, the above output result appears.
2. What is the output result of this code?
public class Test {Person person = new Person("Test");static{System.out.println("test static");}public Test() {System.out.println("test constructor");}public static void main(String[] args) {new MyClass();}}class Person{static{System.out.println("person static");}public Person(String str) {System.out.println("person "+str);}}class MyClass extends Test {Person person = new Person("MyClass");static{System.out.println("myclass static");}public MyClass() {System.out.println("myclass constructor");}} test static 1
test static 2
Although there are no statements in the main method, they will still output, because the reason has been explained above. In addition, the static block can appear anywhere in the class (as long as it is not inside the method, remember, no method can do it) and the execution is executed in the order of the static blocks.
The above is a comprehensive analysis of the static keywords in Java introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!