Besides, the final variable

Source: Internet
Author: User

From JDK to today, Java technology has undergone tremendous technological changes after more than a decade of development. However, the definition of final Variables

Since its birth, no changes have taken place, that is, over the past 10 years, it has always expressed its original meaning.

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, final stringbuffer sb = new stringbuffer ("axman ");
SB = new stringbuffer ("Sager"); // error. SB cannot point to other objects.
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:

Java code
  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]);
Public static void test (INT [] X) {x = new int [] {, 3 };} int [] out = new int [] {, 6 }; test (out); system. out. println (out [0]); system. out. println (out [1]); 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:

Java code
  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]);
Public static void test (final int [] X) {x [0] = 100;} int [] out = new int [] {, 6}; test (out ); 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,
Callback method passed to internal class:

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

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

Java code
  1. Public static void test (string s ){
  2. // Or string S = "";
  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. }
Public static void test (string s) {// or string S = ""; absclass c = new absclass () {public void M () {int x = S. hashcode (); system. out. println (x) ;}}; // other code .}

Note that the callback method is generally called in other threads.

Java code
  1. Absclass c = new absclass (){
  2. Public void M (){
  3. Int x = S. hashcode ();
  4. System. Out. println (X );
  5. }
  6. };
Absclass c = new absclass () {public void M () {int x = S. hashcode (); system. Out. println (x );}};

The subsequent direct call of C. M (); should be meaningless. But this is not important. The important thing is that as long as it may be called in other threads, we must

Saves the reference handle for S.

Let's take a look at the working principle of GC. Every process in jvm has multiple roots, each static variable, method parameter, and local variable. Of course, this is a guiding type.
The basic type cannot be the root, but the root is actually a storage address.

When GC is working, it first traverses the referenced objects from the root and marks them, so that the recursion is to the final end. After all the roots are traversed, the objects not marked are not described.
Objects that can be recycled (some objects have the finalized method, although not referenced, but the JVM has a dedicated queue to reference it)
They are not removed from the queue until the finalized method is executed and can be recycled. This is irrelevant to the topic, including
The division of generation will be explained later). This looks good.

However, in the callback method of the internal class, S is neither a static variable nor a temporary variable in the method, nor a method parameter. It cannot be used as the root of the internal class.
There is no variable to reference it. In the internal class external method, if the external variable points to another object, the object will lose the reference,
It may be recycled. Because most of the internal class callback methods are executed in other threads, they may still be accessed after being recycled. What is the result?

Using the final modifier will not only keep the object unchanged, but also the compiler will continue to maintain the lifecycle of this object in the callback method. Therefore, this is final.
The fundamental significance of variables and final parameters.

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.