In Java, static is a modifier, used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance; methods or variables modified by the static keyword are not It needs to rely on the object for access. As long as the class is loaded, it can be accessed through the class name.
(Recommended tutorial: java introductory tutorial)
1. Characteristics of the static keyword:
There is this passage on page P86 of "Java Programming Thoughts":
"A static method is a method without this. Non-static methods cannot be called inside a static method, and the reverse is possible. And You can call the static method only through the class itself without creating any objects. This is actually the main purpose of the static method."
Although this paragraph only explains the static method Special feature, but you can see the basic function of the static keyword. In short, the description in one sentence is:
It is convenient to call (method/variable) without creating an object.
Obviously, methods or variables modified by the static keyword do not need to rely on objects for access. As long as the class is loaded, it can be accessed through the class name.
static is a modifier used to modify class member methods and class member variables. In addition, static code blocks can be written to optimize program performance;
(Video tutorial recommendation: java video tutorial)
1. Static modified member method
Static modified methods are generally called static methods. Since static methods can be accessed without relying on any object, so for For static methods, there is no this, because it is not attached to any object. Since there is no object, there is no 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 before they can 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. For example:
#In the above code, since the print2 method exists independently of the object, it can be called directly with the 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 are no objects, and str2 does not exist at all, so a contradiction will occur. The same is true for methods. Since you cannot predict whether non-static member variables are accessed in the print1 method, accessing non-static member methods in static member methods is also prohibited.
For non-static member methods, there is obviously no restriction on 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. As for why the main method must be static, it is now clear. Because the program does not create any objects when executing the main method, it can only be accessed through the class name.
2. Static modified member variables
Static modified variables are also called static variables. The difference between static variables and non-static variables is that static variables are shared by all objects and there is only one in the memory. A copy that will be initialized if and only if the class is first loaded. Non-static variables are owned by objects and 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 modified code block
Another important role of the static keyword is to form a static code block to optimize program performance. A static block can be placed anywhere in a class, and there can be multiple static blocks in a class. When a class is loaded for the first time, each static block will be executed in the order of the static blocks, and will only be executed once.
Static block can optimize program performance because of its characteristics: it will only be executed once when the class is loaded for the first time. As follows:
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 determine whether a person was born between 1946 and 1964. Every time isBornBoomer is called, two objects, startDate and birthDate, will be generated, causing a waste of space. If you change It will be more efficient as follows:
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, many initialization operations that only need to be performed once are placed in static code blocks.
二、static關(guān)鍵字的誤區(qū)
1. 與C/C++中的static不同,Java中的static關(guān)鍵字不會影響到變量的變量或者方法的作用域。在Java中能夠影響到訪問權(quán)限的只有private、public、protected這幾個關(guān)鍵字。示例如下:
提示錯誤,說明static關(guān)鍵字并不會改變變量和方法的訪問權(quán)限。
2. 雖然對于靜態(tài)方法來說沒有this,但是我們在非靜態(tài)方法中能夠通過this訪問靜態(tài)方法成員變量。如下:
public class Test { static int value = 11; public static void main(String[] args) { new Test().printValue(); } private void printValue() { int value = 22; System.out.println(this.value); } }
輸出的結(jié)果是:11
這里的this表示的是當(dāng)前對象,那么通過new Test()來調(diào)用printValue的話,當(dāng)前對象就是通過new Test()生成的對象。而static變量是被對象所享有的,因此在printValue中的this.value的值毫無疑問是11。在printValue方法內(nèi)部的value是局部變量,根本不可能與this關(guān)聯(lián),所以輸出11。需要記住的是:靜態(tài)成員變量雖然獨立于對象,但是不代表不可以通過對象去訪問,所有的靜態(tài)方法和靜態(tài)變量都可以通過對象訪問(只要權(quán)限足夠)。
3. 在C/C++中static關(guān)鍵字是可以作用于局部變量的,但是在Java中是不允許使用static修飾局部變量的。這是Java語法的規(guī)定。
更多編程相關(guān)知識,請訪問:編程教學(xué)??!
The above is the detailed content of What is the function of java static keyword?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor
