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

The principle and Application of final keyword in Java

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "the principle and application of final keyword in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn the principle and application of the final keyword in Java.

Final is one of the most important keywords in Java, which can be applied to classes, methods, and variables. What is the final keyword in this article? What does declaring variables, methods, and classes as final represent? What are the benefits of using final?

What is the final keyword?

Final is a reserved keyword in Java that declares member variables, methods, classes, and local variables. Once you declare the reference as final, you will not be able to change the reference. The compiler will check the code and report a compilation error if you try to initialize the variable again.

Final variable

Any final that is declared as a member variable or a local variable (a variable in a method or code block is called a local variable) is called a final variable. The final variable is often used with the static keyword as a constant. Here is an example of the final variable:

Public static final String NAME = "wupx"; NAME = new String ("wupx"); / / invalid compilation error

The final variable is read-only.

Final method

Final can also declare a method, and the only correct use for decorating a method with the final modifier in Java is to express: this method, originally a virtual method, is now declared through final that it does not allow further override in derived classes.

Non-private member methods in Java are virtual methods by default, and virtual methods can be overridden in derived classes. To ensure that a virtual method on a class is not further overridden in a derived class, you need to use the final modifier to declare it and have the compiler (such as javac) check with JVM to ensure that this restriction is always true.

The following quotes R Da's answer on Zhihu to break the myth that "using the final modification method can make the call to this method faster":

There used to be a widely circulated saying that using final embellishments can make calls to this method faster. This statement is not true on modern mainstream optimized JVM (for example, Oracle JDK / OpenJDK HotSpot VM, IBM J9 VM, Azul Systems Zing VM, etc.). This is because it is impossible for a virtual method that can be modified with final to have an overridden version in its derived class, so it can be determined that this virtual method has only one possible calling target. If the final modifier is removed at this time, these advanced JVM can use Class Analytic hierarchy process (Class Hierarchy Analysis,CHA) to find that there is no further overridden version of the method in the derived class, so it can also be determined that the virtual method has only one possible calling target. Then the degree of optimization of the two will be exactly the same, whether from the point of view of "calling the target directly without virtual dispatch" (called "de-virtual", devirtualization) or from the perspective of "easy inlining".

If there are multiple overridden versions of a virtual method in a class hierarchy, it would not be possible to add final modification to the virtual method, so even if de-virtual becomes difficult in this case, the pot should not be memorized "because there is no final modification".

Using the final keyword does not improve performance on modern mainstream optimized JVM.

Here is an example of the final method:

Class User {public final String getName () {return "user:wupx";}} class Reader extends User {@ Override public final String getName () {return "reader wupx"; / / compilation error: overridden method is final}} final class

Classes decorated with final are called final classes. Final classes are usually fully functional and cannot be inherited. Many classes in Java are final, such as String, Interger, and other wrapper classes. Here is an example of the final class:

Final in final class User {} class Reader extends User {/ / compilation error: cannot inherit from final class} memory model

For final variables, both the compiler and the processor follow two reordering rules:

Constructor, writing to a final variable and then assigning a reference to the constructed object to a variable cannot be reordered between the two operations

Read an object containing a final variable for the first time, and then read the final variable for the first time. There is no reordering between the two operations.

In fact, these two rules are also aimed at writing and reading final variables. The written reordering rule ensures that the object's final variable is initialized correctly before the object reference is visible to any thread, while the ordinary variable does not have this guarantee; the read reordering rule ensures that the object reference will be read before reading the object's final variable. If the read reference is not empty, according to the above write rules, the final variable of the object must be initialized so that the correct variable value can be read.

If the type of final variable is referenced, then writing to the member field of an object referenced by final within the constructor and then assigning a reference to the constructed object to a reference variable outside the constructor cannot be reordered.

In fact, this is also to ensure that the final variable is initialized correctly before it is visible to other threads.

Benefits of the final keyword

Here are some benefits of using the final keyword:

The final keyword improves performance, and both JVM and Java applications cache final variables

Final variables can be safely shared in a multithreaded environment without additional synchronization overhead

Summary

The final keyword can be used for member variables, local variables, methods, and classes

Final member variables must be initialized when declared or in the constructor, otherwise compilation errors are reported

Cannot assign a value to final variable again

Local variables must be assigned when declared

All variables in an anonymous class must be final variables

The final method cannot be overridden

The final class cannot be inherited

All variables declared in the interface are themselves final

If the keywords final and abstract are inversely related, it is impossible for the final class to be abstract

Blank final variables (blank final variable) are called blank final variables that are not initialized on declaration. They must be initialized in the constructor or initialized by calling this (). Otherwise, the compiler will report that the final variable (variable name) needs to be initialized

According to Java code conventions, final variables are constants, and the common name of the quantity should be capitalized

Declaration as final for collection objects means that references cannot be changed

At this point, I believe you have a deeper understanding of the principle and application of the final keyword in Java. You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Internet Technology

Wechat

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

12
Report