Introduction:
When it comes to the final keyword, it's probably a lot of people who are not unfamiliar with the final keyword when using anonymous internal classes. In addition, the string class in Java is a final class, so today we'll look at the use of the final keyword.
The directory outline of this article:
I. Basic usage of the final keyword
1. Modifier class
2. Modification methods
3. Modifier variables
Two. In-depth understanding of final keywords
1. What is the difference between a class's final variable and a normal variable?
2. Is the content of the object pointed to by the final modified reference variable variable?
3.final and Static
4. Why is an external local variable used in an anonymous inner class only a final variable?
5. Questions about the final parameter
basic usage of the final keyword
1. Modifier class
When a class is decorated with final, it indicates that the class cannot be inherited. In other words, if a class you never let him inherit, you can use final to decorate. Member variables 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 the final method.
When using the final modifier class, be careful to choose, unless the class is not intended to be inherited later or for security reasons, try not to design the class as the final class.
2. Modification methods
The following is part of the fourth edition of Java Programming thought, page 143th:
There are two reasons for using the final method. The first reason is to lock the method in case any inherited class modifies its meaning, and the second reason is efficiency. In earlier versions of Java implementations, the final method was converted to inline invocation. However, if the method is too large, you may not see any performance gains from inline calls. In the recent Java release, these optimizations do not need to be made using the final method. “
Therefore, the method is set to final only if you want to explicitly prohibit the method from being overwritten in the subclass.
Note: The private method of the class is implicitly specified as the final method.
3. Modifier variables
The modified variable is the most used place in final use, and it is also the focus of this article. First look at the basic syntax of the final variable:
For a final variable, if it is a variable of the base data type, its value cannot be changed once initialized, and if it is a variable of a reference type, it cannot be pointed to another object after it has been initialized.
As an example:
In the above section of the code, the re-assignment of the variables I and obj is an error.
understand final keywords in depth
After understanding the basic usage of the final keyword, let's look at where the final keyword is easy to confuse.
1. What is the difference between a class's final variable and a normal variable?
When you use final action on a member variable of a class, the member variable (note is the member variable of the class, the local variable needs to be guaranteed to be initialized before use) must be assigned in the definition or constructor, and once the final variable is initialized, it can no longer be assigned a value.
So what is the difference between a final variable and a normal variable? Let's take a look at the following example:
Public class Test { publicstaticvoid main (string[] args) { = "Hello2" ; Final String b = "Hello"; = "Hello"; = B + 2; = d + 2; = = c)) ; = = e));} }
true false
View Code
We can first think about the output of this problem. Why the first comparison result is true, and the second compares the result to Fasle. This is the difference between the final variable and the normal variable, when the final variable is the base data type and the string type, if you can know its exact 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 that is accessed directly, and does not need to be determined at run time. This is a bit like a macro substitution in C language. So in the preceding section of code, because the variable B is final decorated, it is treated as a compiler constant, so where B is used, the variable b is replaced directly with its value. The access to variable D needs to be linked at run time. Presumably the difference should be understood, but note that the compiler does this only if the final variable value is known exactly during compilation, as the following code does not optimize:
Class Test { public static void main (string[] args) {Strin G 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.
2. Is the content of the object pointed to by the final modified reference variable variable?
In the above mentioned the final modified reference variable once the initialization of the assignment can no longer point to other objects, then the reference variable point to the contents of the object is variable? Look at the following example:
Public class Test { publicstaticvoid main (string[] args) { Finalnew MyClass (); System.out.println (+ +myclass.i) ; class MyClass { publicint i = 0;}
This code can be successfully compiled and has output results, the output is 1. This means that after the reference variable is final decorated, it cannot point to another object, but the contents of the object it points to are mutable.
3.final and Static
Many times it is easy to confuse the static with the final keyword, where static acts on the member variable to indicate that only one copy is saved, and final is used to ensure that the variable is immutable. Look at the following example:
Public classTest { Public Static voidMain (string[] args) {MyClass MyClass1=NewMyClass (); MyClass MyClass2=NewMyClass (); System.out.println (MYCLASS1.I); System.out.println (MYCLASS1.J); System.out.println (MYCLASS2.I); System.out.println (MYCLASS2.J); }} classMyClass { Public Final Doublei =Math.random (); Public Static Doublej =math.random ();}
Running this code will reveal that the two J values are the same for each print, while the value of I is different. From here you can see the difference between final and static variables.
4. Why is an external local variable used in an anonymous inner class only a final variable?
This question is explained in the previous Article blog post, "Inside the Java class," which is not described here.
5. Questions about the final parameter
On the Internet "when you do not need to change an object variable as a parameter in a method, it is not appropriate to explicitly use Final declaration, which will prevent you from inadvertently modifying a variable outside of the calling method".
Because either the argument is a variable of the base data type or a variable of a reference type, using the final declaration does not achieve the effect described above.
See this example to make it clear:
The above code seems to make it possible to change the value of the variable I in the method after the final modification. As everyone knows, the method ChangeValue and the main method of the variable i is not a variable, because the Java parameter is passed by the value of the pass, for the basic type of variable, the equivalent of a direct copy of the variable. So even without final modification, changing the value of the variable I within the method does not affect the I outside of the method.
Let's look at the following code:
Public classTest { Public Static voidMain (string[] args) {MyClass MyClass=NewMyClass (); StringBuffer Buffer=NewStringBuffer ("Hello"); Myclass.changevalue (buffer); System.out.println (Buffer.tostring ()); }} classMyClass {voidChangeValue (FinalStringBuffer Buffer) {Buffer.append ("World"); }}
Running this code will reveal that the output is HelloWorld. Obviously, finishing with final does not prevent changing the contents of the object that the buffer points to in ChangeValue. Some say that if the final is removed, what if buffer is pointed to other objects in the ChangeValue. Friends with this idea can write their own code to try what the result is, if the final is removed, and then in the ChangeValue to point buffer to other objects, and does not affect the buffer in the main method, because Java is based on value passing, For reference variables, the reference value is passed, which means that the argument and the parameter point to the same object simultaneously, so that having the parameter point back to the other object has no effect on the argument.
Therefore, I personally do not agree with the statement on the final parameters circulated on the Internet.
Resources:
The idea of Java programming
A brief analysis of final keywords in Java