Usage of final

Source: Internet
Author: User
Document directory
  • Final

From jdk1.0 to today, Java technology has undergone tremendous technological changes after more than a decade of development. however, the definition of final variables has not changed since its birth, that is, it has been representing its original meaning for more than a decade. unfortunately, after more than a decade, 90% of people still do not understand the true meaning of it, nor have they published an article, including all the introductions I have seen.

Java books (including tkj) are not clear. I believe some authors understand this, but none of them tell readers clearly. Chinese netizens
Most people have been beaten by an article about <talking about final, finalized, finally> in Java ).

The definition of final variables is not complex, that is, once initialized, variables cannot point to other objects. In C ++, they are a const pointer, and
It is not a pointer to the const variable. The const pointer means that it can only always point to the address at the time of initialization, but the object in that address itself
The pointer to the const variable indicates that the object itself cannot be modified.

For example:

  1. Final stringbuffer sb = new stringbuffer ("axman ");
  2. SB = new stringbuffer ("Sager"); // error. SB cannot point to other objects.
  3. SB. append ("was changed! "); // The earth object to which sb points can be modified.

Let's first talk about final variable initialization:

Many articles have said this: the initialization can be in two places: one is its definition, and the other is in the constructor. Either of them can be selected.
Nonsense!
Final variables can be initialized at any place where they can be initialized, but can only be initialized once. Once initialized, they cannot be assigned again.
Value (re-pointing to other objects), must be explicitly initialized as a member variable, while as a temporary variable, you can only define and do not initialize (of course, cannot reference)
Even as a member variable in a class, it can also be initialized in the initialization block, so "the initialization can be in two places. One is its definition,
Second, in the constructor, either of the two can be "Incorrect.

As a member variable, the final field can be designed as a non-variable class, which is a required condition but not a sufficient condition. At least it can ensure that the field is not
It will be changed in the form of setxxx (), but it cannot be ensured that the field itself is not modified (unless the field itself is also a constant class );

For final variables of method parameters:
If the variables of method parameters are defined as final, more than 90% of the articles say, "when you do not need to change the object variables used as parameters in methods, make it clear
Using final statements will prevent you from accidentally modifying the variables outside the calling method. "
Nonsense!

I don't know whether this modification refers to re-assigning the value or modifying the object itself, but in either case, the above statement is wrong.
If the value is re-assigned, then:

  1. Public static void test (INT [] X ){
  2. X = new int [] {1, 2, 3 };
  3. }
  4. Int [] out = new int [] {4, 5, 6 };
  5. Test (out );
  6. System. Out. println (out [0]);
  7. System. Out. println (out [1]);
  8. System. Out. println (out [2]);

Call test (out); in any case, it will not affect the out variable. It doesn't make sense if you add final. Final will only force the Method
Declare one more variable name, that is, change x = new int [] {1, 2, 3}; to int y = new int [] {1, 2, 3 }; nothing else actually makes sense.
If it is to modify the object itself:

  1. Public static void test (final int [] X ){
  2. X [0] = 100;
  3. }
  4. Int [] out = new int [] {4, 5, 6 };
  5. Test (out );
  6. System. Out. println (out [0]);

Can't you modify the final modification? Therefore, the final in the method parameters is used to avoid affecting the variables outside the called method.

So why should we add final to the parameter? In fact, adding final to method parameters is the same as adding final to method variables, that is,
Ensure the call consistency when passed to the internal class:

  1. Abstract class absclass {
  2. Public abstract void M ();
  3. }

Now, if I want to implement an anonymous call to absclass in a method, we should:

  1. Public static void test (final string s ){
  2. // Or final string S = "axman ";
  3. Absclass c = new absclass (){
  4. Public void M (){
  5. Int x = S. hashcode ();
  6. System. Out. println (X );
  7. }
  8. };
  9. // Other code.
  10. }
  11. // The code is actually compiled:
  12. Public static void test (final string s ){
  13. // Or final string S = "axman ";
  14. Absclass c = new absclass (s ){
  15. Private final string S;
  16. Public absclass (string s ){
  17. This. S = s;
  18. }
  19. Public void M (){
  20. Int x = S. hashcode ();
  21. System. Out. println (X );
  22. }
  23. };
  24. // Other code.
  25. }

That is, the variable of the external class is passed to the private member of the internal class as the parameter of the constructor.
If there is no final, then:

  1. Public static void test (string s ){
  2. // Or string S = "axman ";
  3. Absclass c = new absclass (){
  4. Public void M (){
  5. S = "other ";
  6. }
  7. };
  8. System. Out. println (s );
  9. }
  10. // It will be compiled:
  11. Public static void test (string s ){
  12. // Or string S = "axman ";
  13. Absclass c = new absclass (s ){
  14. Private final string S;
  15. Public absclass (string s ){
  16. This. S = s;
  17. }
  18. Public void M (){
  19. S = "other ";
  20. }
  21. };
  22. System. Out. println (s );
  23. }
  24. // The S of the internal class points to "other" and does not affect the test parameter or the S defined externally. What you see
  25. Public static void test (string s ){
  26. // Or string S = "axman ";
  27. Absclass c = new absclass (){
  28. Public void M (){
  29. S = "other ";
  30. }
  31. };
  32. System. Out. println (s );
  33. }

The syntax is a second, which is changed in the internal class, but the result is printed and you think it is the same s, but it is still the original "axman ",
Can you receive such results?
Therefore, final restricts the consistency of two different variables in syntax.

 

========================================================== ========================================================== ======================================

Another article

Final

Final is not commonly used in Java, but it provides functions such as defining constants in C language, final also allows you to control whether your members, methods, or a class can be overwritten or inherited. These features enable final to play an indispensable role in Java, it is also one of the keywords that must be known and mastered when learning Java.
Final member
When you define a variable in a class and add the final keyword before it, this variable cannot be changed once initialized, the unchangeable meaning here is that its value is immutable for the basic type, and its reference for the object variable cannot be changed. It can be initialized in two places. One is its definition, that is, it is assigned a value directly when the final variable is defined, and the other is in the constructor. You can only choose one of these two places, either give a value at the time of definition, or give a value in the constructor, not both at the time of definition, in the constructor, another value is given. The following code demonstrates this point:

  1. ImportJava. util.List;
  2. ImportJava. util.Arraylist;
  3. ImportJava. util.Shortlist;
  4. Public ClassBat {
  5. FinalPi = 3.14;// The address value is assigned at the time of definition.
  6. Final IntI;// Because Initialization is required in the constructor, no value can be given here
  7. Final ListList;// This variable is the same as the above variable.
  8. BAT (){
  9. I = 100;
  10. List =New Shortlist();
  11. }
  12. BAT (IntII,ListL ){
  13. I = II;
  14. List = L;
  15. }
  16. Public Static VoidMain (String[] ARGs ){
  17. Bat B =NewBAT ();
  18. B. List. Add (NewBAT ());
  19. // B. I = 25;
  20. // B. List = new arraylist ();
  21. System. Out. println ("I =" + B. I + "list type:" + B. List. getclass ());
  22. B =NewBAT (23,New Arraylist());
  23. B. List. Add (NewBAT ());
  24. System. Out. println ("I =" + B. I + "list type:" + B. List. getclass ());
  25. }
  26. }

This program demonstrates the general usage of final. Here we use the initialization method in the constructor, which gives you a little flexibility. As shown in the two overloaded constructors of BAT, the first default constructor will provide you with the default value. The overloaded constructor will initialize the final variable based on the value or type you provided. However, sometimes you don't need this flexibility. You just need to set the value at the time of definition and never change. In this case, you don't need to use this method. There are two lines of statements commented out in the main method. If you remove the comment, the program will not be able to compile. This is to say, whether it is the value of I or the type of list, once initialized, it cannot be changed. However, B can specify the I value or list type through reinitialization. This is shown in the output:
I = 100 list type: Class java. util. Category list
I = 23 list type: Class java. util. arraylist
Another method is to define the final parameter in the method. For variables of the basic type, this method has no practical significance, because the variables of the basic type are passed values when calling the method, that is to say, you can change this parameter variable in the method without affecting the call statement. However, it is very practical for the object variable because the object variable is passed with its reference during transmission, in this way, your modification to the object variable in the method will also affect the object variable in the call statement. When you do not need to change the object variable used as the parameter in the method, use final to declare it, it will prevent you from accidentally modifying the call method.
In addition, when the internal class in the method uses the variable in the method, this parameter must be declared as final for use, as shown in the following code:

  1. Public ClassInclass {
  2. VoidInnerclass (Final StringStr ){
  3. ClassIclass {
  4. Iclass (){
  5. System. Out. println (STR );
  6. }
  7. }
  8. Iclass Ic =NewIclass ();
  9. }
  10. Public Static VoidMain (String[] ARGs ){
  11. Inclass Inc =NewInclass ();
  12. Inc. innerclass ("hello ");
  13. }
  14. }

Final Method
If you declare the method as final, it means that you already know that the function provided by this method has met your requirements and does not need to be extended, this method cannot be overwritten by any class inherited from this class, but inheritance can still inherit this method, that is, it can be used directly. In addition, there is a mechanism called inline, which enables you to directly Insert the method subject into the call when calling the final method, rather than performing routine method calls, such as saving breakpoints, this may improve the program efficiency. However, when your method subject is very large, or you call this method in multiple places, your calling subject code will expand rapidly, which may affect the efficiency. Therefore, use final for method definition with caution.

Final class
When using final on a class, you need to consider it carefully. Because a final class cannot be inherited by anyone, it means that this class is a leaf class in an inheritance tree, in addition, such designs have been considered perfect without modification or expansion. For members in the final class, you can define it as final or not final. For methods, because the class is final, they naturally become final. You can also explicitly add a final to the methods in the final class, but this is obviously meaningless.
The following program demonstrates the usage of the final method and final class:

  1. Final Class Final{
  2. Final StringSTR = "final data ";
  3. Public StringStr1 = "non final data ";
  4. Final Public VoidPrint (){
  5. System. Out. println ("final method .");
  6. }
  7. Public VoidWhat (){
  8. System. Out. println (STR + "/N" + str1 );
  9. }
  10. }
  11. Public ClassFinaldemo {// Extends final cannot be inherited
  12. Public Static VoidMain (String[] ARGs ){
  13. FinalF =New Final();
  14. F. What ();
  15. F. Print ();
  16. }
  17. }

It can be seen from the program that there is almost no difference between the use of final classes and common classes, but it loses its inherited features. The difference between the final method and the non-final method is also difficult to see from the program line, just remember to use it with caution.
Application of final in Design Mode
In the design pattern, there is a pattern called the immutable pattern. in Java, this pattern can be easily implemented through the final keyword. It explains the program bat used by final members. java is an example of the unchanged mode. If you are interested in this, you can refer to the explanation in the book "Java and mode" written by Dr. Yu Hong.

So far, the use of this, static, supert and final has been completed. If you have been able to roughly express the differences and usage of these four keywords, it means that you have mastered it. However, nothing in the world is perfect. Java provides these four keywords, which brings great convenience to the programming of programmers, but it does not mean that you should use them everywhere, once an abused program is reached, it is counterproductive. Therefore, you must carefully consider it when using it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.