Java Fundamentals (iii)-final keyword analysis

Source: Internet
Author: User

Today to talk about the role of the final keyword, although there are a lot of posts about final has been very deep research, but still have to record to talk about their own views deepened under the impression. Go directly to the following topics:

First, the role of the final keyword

  1. A class that is final modified cannot be inherited.

This should be known to many people have encountered, the classic case is the Java.lang.String class

There are also some common classes that have been modified by the final, as follows:

The type of wrapper that corresponds to the base type (such as Java.lang.Integer, Java.lang.Long, etc.), character-related classes (Java.lang.StringBuilder, Java.lang.StringBuffer), System classes (Java.lang.Class, Java.lang.System) and so on. These others are listed on their own usual to find.

So the question is, a, why is the final modified class not inherited? A: This is a Java syntax definition, can't.

b, what is the purpose of this design? Answer: Because the class does not need to be extended class, implementation details are not allowed to change, it is estimated to be for security reasons.

  2. The final modified method cannot be rewritten

Actually this is also the Java grammar stipulation, cannot do the explanation. But carefully recalled, this situation is similar to the static keyword modification method, and cannot be overridden (overwritten).

Let's look at the case (the code is most impressed by its own knock):

class myclass{    finalvoid  Test () {        System.out.println ("Finalclass");}    }  classextends  MyClass {    // Compile Error: cannot override the final Method from MyClass public    void Test () {        System.out.println ("Finalclass");    } }

3. The final modified variable cannot be "changed"

First, the premise 1: The final modified variable is not like static. It can also modify local variables.

Prerequisite 2: The final modified variable must be initialized, or the compilation will not pass.

For the premise, we first prove by case:

1  Public classFinaltest {2     //compilation failed with precondition 2 not met. The blank final field count may not be been initialized3     Final intcount;4      Public Static voidMain (string[] args) {5         //compiled by. Premise 1: The final modified variable is not like static. It can also modify local variables. 6         Final intt = 0;7     }8}

There are two types of initialization: direct initialization and initialization in the constructor (each constructor initializes the entry for each instantiated object).

 Public classFinaltest {//Direct Initialization    Final intCount = 0; Final intnum; //constructor is initialized, and if Num is not initialized, an error is compiled. The Blank final field num may not be been initialized     Publicfinaltest () {num= 0;//Note This will allow you to see the error message    }     PublicFinaltest (intt) {num= 0; //This ();//these two lines are opened around the same way to not error.     }}

Return to focus, the variable that is final modified, what does it not change? Is the value of a variable a reference to a variable or neither? Seems a bit iffy (is not some of their own did not consider), in fact, is also very simple (usually more attention on the line). In turn, the following example proves:

Case 1 (example of a basic type):

1  Public classFinaltest {2     Final intCount = 0;3     4      Public intGetCount () {5         //The final field Finaltest.count cannot be assigned6         return count + +;7     }8     9      Public Static voidMain (string[] args) {TenFinaltest T =Newfinaltest (); One System.out.println (T.getcount ()); A     } -}

The sixth line in the code above is an error (the final field Finaltest.count cannot be assigned), so it is possible to know that the value of this basic type of variable is not changed after final modification.
Case 2 (Take the object as an example):

1 classCount {2     intCount = 0;3      Public intGetCount () {4         return++count;5     }6 }7 8  Public classFinaltest {9     Ten      Public Static voidMain (string[] args) { One         FinalCount count1 =NewCount (); A         FinalCount Count2 =NewCount (); - System.out.println (Count1.getcount ()); - System.out.println (Count2.getcount ()); the         //The final local variable count1 cannot be assigned. It must is blank and not using a compound assignment -         count1 = Count2; -     } -}

The 16th line has the same error message, but this is a bit different: the value of the member inside the object can be changed. so for this kind of object variable, the variable is a reference to the variables, not the contents of the variable, when the final modification is immutable.

Summarize this: The basic type variable that is final modified, its value is immutable. A reference-type variable that is final modified, whose reference address is immutable, and the contents of the object are mutable.

II. Expansion of final keywords

1. Use an external variable within an anonymous class, the variable must be final decorated.    in the following case, the 10th will compile an error, suggesting that it must be the final modified variable.

1  Public classFinaltest {2     3      Public Static voidMain (string[] args) {4         intCount = 0;5         6Thread Thread1 =NewThread (NewRunnable () {7 @Override8              Public voidrun () {9                 //cannot refer to the Non-final local variable count defined in an enclosing scopeTen                count + +; One             } A         }); -     } -}

  2, in fact, final can also modify the formal parameters. The main purpose of this is to prevent unintentional modifications that affect variables outside of the calling method. If you don't understand this, you don't know what the 3rd role is.

1 classCount {2     intCount = 0;3      Public intGetCount () {4         return++count;5     }6 }7 8  Public classFinaltest {9     intnum = 0;Ten      Public Static voidMain (string[] args) { One         FinalCount Count =NewCount (); A Addcount (count); - System.out.println (count.count); -     } the      Public Static voidAddcount (Finalcount Count) { - Count.getcount ();//count = new count ();//This is tampering.  -     } +}

  3. What is the difference between final and normal variables, and when can they be equal? look at the code below to see what the code is going to output.

1  Public classFinalTest2 {2 3      Public Static voidMain (string[] args) {4         FinalString str1 = "Test";5         FinalString str2 =getcontent ();6String STR3 = "Test";7         8String STR4 = str1 + "";9String STR5 = str2 + "";Ten          OneSystem.out.println (STR3 = =STR4); ASystem.out.println (STR3 = =STR5); -     } -      Public StaticString getcontent () { the         return"Test"; -     } -}

The result after the output is true and false. What is this for? Explain that you know the difference between the two. If it is a string or base type that is defined directly by the final decoration, it determines its value during compilation, and the compiler will treat it as a constant. So when there is a place to use it, it is replaced directly with a constant. Other values are determined by the runtime, so the variables are still used to calculate. STR2 a variable in the code, although it is final decorated but its value is to be determined at run time, it is equivalent to a normal variable. Str5 This method of calculation is not as simple as we think, because str2 is a normal variable here, so the value of the entire expression is calculated by Stringbulider, so the return is also a new STR, the reference address has changed. So the output of line 12th is false;

  4. The difference between final and finally and finalize

Finally is part of the exception-handling statement structure that represents the final execution.

Finalize is a method of the object class that, when executed by the garbage collector, invokes this method of the reclaimed object for other resources at garbage collection, such as closing the file.   

Java Fundamentals (iii)-final keyword analysis

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.