In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to use the final keyword in Java, aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
I. the basic usage of the final keyword
In Java, the final keyword can be used to modify classes, methods, and variables (including member and local variables). Let's take a look at the basic usage of the final keyword from these three aspects.
1. Modifier class
When you modify a class with final, it indicates that the class cannot be inherited. In other words, if a class you will never let it be inherited, you can modify it with final. The member variable in the final class can be set to final as needed, but note that all member methods in the final class are implicitly specified as final methods.
Be careful when using final to modify a class, unless the class is really not used for inheritance or for security reasons, try not to design the class as a final class.
two。 Modification method
The following is an excerpt from page 143 of Java programming ideas, fourth edition:
"the final method is used for two reasons. The first reason is to lock the method to prevent any inherited class from changing its meaning; the second reason is efficiency. In earlier versions of the Java implementation, the final method was converted to an inline call. But if the method is too large, you may not see any performance improvement from embedded calls. In recent versions of Java, there is no need to use the final method for these optimizations. "
Therefore, set the method to final only if you want to explicitly prohibit the method from being overridden in the subclass.
Note: the private method of the class is implicitly specified as the final method.
3. Modified variable
Decorating variables is the most frequently used part of final, and it is also the focus of this article. First, take a look at the basic syntax of final variables:
For a final variable, if it is a variable of a basic data type, its value cannot be changed once initialized; if it is a variable of a reference type, it cannot point to another object after initialization.
For example:
In the above code, the reassignment of the variables I and obj has been reported incorrectly.
two。 In-depth understanding of final keyword
After understanding the basic usage of the final keyword, let's take a look at the confusion of the final keyword in this section.
1. What is the difference between a final variable of a class and a normal variable?
When using final to act on member variables of a class, member variables (note that they are class member variables, local variables only need to be initialized before use) must be initialized at definition time or in the constructor, and final variables can no longer be assigned once they have been initialized.
So what's the difference between final variables and normal variables? Let's look at an example:
Public class Test {public static void main (String [] args) {String a = "hello2"; final String b = "hello"; String d = "hello"; String c = b + 2; String e = d + 2; System.out.println ((a = = c)); System.out.println ((a = = e));} true
False
You can think about the output of this problem first. Why the first comparison result is true and the second comparison result is fasle. This is the difference between a final variable and an ordinary variable. When a final variable is a basic data type and a String type, if you know its true value during compilation, the compiler will use it as a compile-time constant. That is, where the final variable is used, it is equivalent to the constant accessed directly, and does not need to be determined at run time. This is a bit like macro substitution in C language. So in the above code, because the variable b is modified by final, it is treated as a compiler constant, so the variable b is directly replaced with its value where b is used. Access to the variable d, on the other hand, needs to be linked at run time. You should understand the difference, but note that the compiler does this optimization only if the value of the final variable is known exactly during compilation, such as the following code:
Public class Test {public static void main (String [] args) {String a = "hello2"; final String b = getHello (); String c = b + 2; System.out.println ((a = = c));} public static String getHello () {return "hello";}
The output of this code is false.
two。 Is the content of the object pointed to by the reference variable modified by final changeable?
As mentioned above, once the reference variable modified by final initializes the assignment, it can no longer point to another object, so is the content of the object pointed to by the reference variable changeable? Look at the following example:
Public class Test {public static void main (String [] args) {final MyClass myClass = new MyClass (); System.out.println (+ + myClass.i);}} class MyClass {public int i = 0;}
This code can be compiled smoothly and has the output result, which is 1. This means that after the reference variable is modified by final, it can no longer point to other objects, but the content of the object it points to is mutable.
3.final and static
In many cases, it is easy to confuse the static keyword with the final keyword. Static acts on member variables to indicate that only one copy is saved, while the role of final is to keep the variables immutable. Look at the following example:
Public class Test {public static void main (String [] args) {MyClass myClass1 = new MyClass (); MyClass myClass2 = new MyClass (); System.out.println (myClass1.i); System.out.println (myClass1.j); System.out.println (myClass2.i); System.out.println (myClass2.j);} class MyClass {public final double i = Math.random () Public static double j = Math.random ();}
If you run this code, you will find that the two j values printed each time are the same, while the values of I are different. From here you can see the difference between final and static variables.
4. Why can external local variables used in anonymous inner classes only be final variables?
Please refer to the explanation of this question in "detailed explanation of Java Internal classes" in the previous blog post, and I won't repeat it here.
5. On the problem of final parameters
With regard to the phrase spread on the Internet, "when you do not need to change the object variable as a parameter in the method, explicitly using final for declaration will prevent you from inadvertently modifying and affecting the variable outside the calling method." I personally understand that this is not appropriate.
Because whether the parameter is a variable of the basic data type or a variable of the reference type, using the final declaration will not achieve the effect mentioned above.
Look at this example to make it clear:
The above code seems to give the impression that after being decorated with final, you can't change the value of the variable I in the method. Unexpectedly, the variable I in the changeValue and main methods is not a variable at all, because the java parameter is passed by value, and for the basic type of variable, it is equivalent to copying the variable directly. So even without final modification, changing the value of the variable I inside the method does not affect the I outside the method.
Take a look at the following code:
Public class Test {public static void main (String [] args) {MyClass myClass = new MyClass (); StringBuffer buffer = new StringBuffer ("hello"); myClass.changeValue (buffer); System.out.println (buffer.toString ());}} class MyClass {void changeValue (final StringBuffer buffer) {buffer.append ("world");}}
Run this code and you will find that the output is helloworld. Obviously, decorating with final does not prevent the content of the object pointed to by buffer from being changed in changeValue. Some people say that if you remove final, what if you let buffer point to other objects in changeValue. Friends who have this idea can write their own code to try what the result is. If you remove the final and let buffer point to other objects in changeValue, it will not affect the buffer in the main method, because java uses value passing, and for reference variables, it passes the referenced value, that is to say, let the argument and parameter point to the same object at the same time. So letting the parameter point back to another object has no effect on the argument.
This is the answer to the question about how to use the final keyword in Java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.