Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the static keyword in Java

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail "how to use the static keyword in Java", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to use the static keyword in Java" can help you solve your doubts.

I. the purpose of the static keyword

There is a passage on page P86 of "Java programming ideas":

"static methods are methods without this. Non-static methods cannot be called within static methods, and vice versa. And you can call static methods only through the class itself without creating any objects. This is actually the main purpose of static methods."

Although this passage only illustrates the special features of the static method, you can see the basic function of the static keyword. In short, it can be described in one sentence:

It is convenient to make calls (methods / variables) without creating an object.

Obviously, methods or variables modified by the static keyword do not need to rely on the object for access, as long as the class is loaded, it can be accessed through the class name.

Static can be used to modify class member methods, class member variables, and you can write static code blocks to optimize program performance.

1) static method

Static methods are generally called static methods. Because static methods can be accessed without relying on any object, there is no this for static methods, because they are not attached to any objects. Since there are no objects, there is no this. And because of this feature, the 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 before they can be called.

Note, however, 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. Take 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 you have the following statement in the main method:

MyObject.print2 ()

At this point, there are no objects, and the str2 does not exist at all, so there will be contradictions. The same is true for methods, because you can't predict whether non-static member variables are accessed in print1 methods, so access to non-static member methods is also prohibited in static member methods.

For non-static member methods, access to static member methods / variables is obviously unrestricted.

Therefore, if you want to call a method without creating an object, you can set the method to static. Our most common static method is the main method, and it is now clear why the main method must be static. Because the program does not create any objects when it executes the main method, it can only be accessed through the class name.

Also remember, about whether the constructor is a static method, please refer to: http://blog.csdn.net/qq_17864929/article/details/48006835

2) static variable

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, have only one copy in memory, and are initialized only when the class is first loaded. Non-static variables are owned by the object, are initialized when the object is created, 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 order defined.

3) static code block

Another key function of the static keyword is to form static blocks of code to optimize program performance. Static blocks can be placed anywhere in a class, and there can be multiple static blocks in a class. When the class is first loaded, each static block is executed in the order of the static blocks, and only once.

The reason why the static block can be used to optimize program performance is that it is executed 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是用来这个人是否是1946-1964年出生的,而每次isBornBoomer被调用的时候,都会生成startDate和birthDate两个对象,造成了空间浪费,如果改成这样效率会更好: 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;}}

Therefore, in many cases, initialization operations that only need to be done once will be carried out in the static code block.

II. The misunderstanding of the static keyword will the 1.static keyword change the access of members of the class?

Some beginners will confuse the function of the static keyword in java with the keyword "static" in Candlespace +. Just remember here that the static keyword in Java does not affect the scope of a variable or method, unlike static in C _ Java. The only keywords that can affect access in Java are private, public, and protected (including package access). Take a look at the following example:

The error "Person.age is not visible" is prompted, which means that the static keyword does not change the access rights of variables and methods.

two。 Can I access static member variables through this?

Although there is no this for static methods, can static member variables be accessed through this in non-static methods? Let's take a look at the following example. What is the output of this code?

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);}}

thirty-three

This is the understanding of the main expedition team this and static. What does this stand for? This represents the current object, so 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 there is no doubt that the value of this.value in printValue is 33. The value inside the printValue method is a local variable and cannot be associated with this at all, so the output is 33. It is always important to keep in mind here that static member variables are independent of the object, but it does not mean that they cannot be accessed through the object, and all static methods and static variables can be accessed through the object (as long as the access permissions are sufficient).

Can 3.static act on local variables?

Static is scoped to local variables in Java +, but keep in mind that static is not allowed to modify local variables. Don't ask why, it's a rule of Java grammar.

three。 Common written interview questions

The following is a list of some questions about the static keyword that are often encountered in the written interview for reference only. If you have anything to add, please leave a message 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") }}

Base static

Test static

Base constructor

Test constructor

As for why this result is not discussed, let's first think about the specific execution process of this code. At the beginning of execution, we should first find the main method, because the main method is the entrance to the program, but before executing the main method, we must first load the Test class, and when loading the Test class, we find that the Test class inherits from the Base class, so we will load the Base class first. When loading the Base class, we will find that there is a static block. The static block is executed. After the Base class is loaded, it continues to load the Test class, and then finds that there is also a static block in the Test class, and executes the static block. After the required classes are loaded, the main method is executed. When new Test () is executed in the main method, the parent class's constructor is called first, and then its own constructor is called. As a result, the above output appears.

two。 What is the output 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

Myclass static

Person static

Person Test

Test constructor

Person MyClass

Myclass constructor

Similarly, let's think about the execution of this code. The Test class is loaded first, so the static block in the Test class is executed. Then execute new MyClass (), and the MyClass class hasn't been loaded yet, so you need to load the MyClass class. When you load the MyClass class, you find that the MyClass class inherits from the Test class, but because the Test class has already been loaded, you only need to load the MyClass class, and the static block in the MyClass class will be executed. After loading, the object is generated through the constructor. When generating objects, you must first initialize the member variables of the parent class, so Person person = new Person () in Test will be executed, while the Person class has not been loaded, so it will first load the Person class and execute the static block in the Person class, then execute the constructor of the parent class, complete the initialization of the parent class, and then initialize itself, so it will continue to execute Person person = new Person () in MyClass, and finally execute the constructor of MyClass.

3. What is the output of this code? Public class Test {static {System.out.println ("test static 1");} public static void main (String [] args) {} static {System.out.println ("test static 2");}}

Test static 1

Test static 2

Although there are no statements in the main method, it will still be output, for the reasons described above. In addition, static blocks can appear anywhere in the class (as long as they are not inside the method, remember, not inside any method), and execution is performed in the order of the static blocks.

After reading this, the article "how to use static keywords in Java" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report