Final modifiers in Java in-depth study

Source: Internet
Author: User
Tags modifiers

First, the outset

This blog from: http://www.cnblogs.com/yuananyun/

The final modifier is a relatively simple and commonly used modifier in Java, and a modifier that is more "misunderstood". For many Java programmers, most of them just cursory read a variety of books on the introduction, and then back down, when remembered
Just use it if you have this thing. For when to use the final modifier and the final modifier to affect the program, they don't know, of course, before this article, I was smattering.

The final description in our book is about three ways to use it:

      1. Final can modify the variable, and after the final modified variable is assigned the initial value, it cannot be re-assigned to the value

      2. Final can modify the method, the final modified method cannot be overridden

      3. Final can modify the class, the final decorated class cannot be inherited

Here, we will describe the usage of final in these three scenarios in three subsections.

Ii. use of final in variables
(a) The final modified instance variable must display the specified initial value, and the initial value can only be specified in the following three places:
    1. Specifying an initial value when defining a final instance variable
    2. Specifying an initial value for a final instance variable in a non-static initialization block
    3. To specify an initial value for the final instance variable in the constructor

In fact, these three kinds of ways after the compiler processing effect are the same, why? This is because after the compiler processing, the first two ways will be extracted to construct it to assign the initial value, which may be a little deviation from our usual understanding, such as: Final String var1= "I am a Soldier"; Such an instance variable initialization statement, is actually divided into two parts to complete. The first step is to allocate memory for the variable var1 when the object is created, and the second step is to assign the var1 to "I am a soldier" in the constructor, and never assume that the object is created by the constructor, but that the constructor simply completes the initialization of the object.

(b) For a final-modified class variable (static variable), the initial value must also be explicitly specified, and the initial value can only be specified in the following two places:
    1. Specifying an initial value when defining a final class variable
    2. Specifying an initial value for the final class variable in a static initialization block

It should be noted that, after processing by the compiler, both methods are extracted into the static initialization block to assign the initial value.

(c) Final modification of local variables is relatively straightforward, because Java would have required that local variables must be explicitly assigned, unlike ordinary local variables, the final modified local variables once assigned can not be changed.

(iv) In addition, the final modifier can also perform a "macro substitution" of variables that can determine the value of the compilation period, which is what we often call Const constants. For a final variable, whether it is a class variable, an instance variable, or a local variable, as long as the initial value of the variable can be determined at compile time, the final variable is no longer a variable, but rather a direct amount.

 Public Static voidmain (String [] args) {Final intA=5+2; Final DoubleB=1.2/3; FinalString str1= "I am a Soldier"; FinalString str2= "I am" + "a Soldier"; //STR1==STR2 is true because the compile time can determine the value of STR1,STR2, so as a macro replacement: "I am a soldier" = = "I am a soldier", of course, is true        FinalString str3= "I am a Soldier" +string.valueof (99.0); FinalString str4= "I am a soldier 99.0"; //STR3==STR4 is false because STR3 invokes the valueof () function of the string class, which is not deterministic at compile time, so although the string values of STR3 and STR4 are the same, they are not the same object//It also gives a way to determine if a Java string cache is used: if the compilation period is able to determine two or more variables that are strings of the same content,
then they will use the same cached string object.     }

Note: For a macro variable, the effect of a "macro variable" is only given when the variable is defined, and the initial value for the FIANL instance variable is not specified in a non-static code block or in a constructor method. The same is true for static final type variables. It can be understood that when the compiler encounters a final modified variable definition, if it finds that it has a specified initial value, it is treated as an initial value constant, and if not, it cannot be used as a constant. Such as:

 Public classFinalinittest {FinalString str1;FinalString str2;FinalString STR3 = "java" ; {//initializing s in non-static code blocksstr1 = "Java" ;} PublicFinalinittest () {//initialize in constructor methodstr2 = "Java" ;} Public voiddisplay () {System.out.println (str1+ str1 = = "Javajava"); System.out.println (str2+ str2 = = "Javajava"); System.out.println (STR3+ STR3 = = "Javajava");} Public Static voidMain (string[] args) {finalinittest fit=Newfinalinittest (); Fit.display ();} The running result of the program is:falsefalsetrue
Because str1 and str2 do not give initialization values when they are defined, they are later assigned in constructors, so there is no "macro transform" effect

Iii. use of final in methods

When final modifies a method, it is used to restrict the method from being overridden by the quilt class. If a method in the parent class uses the final decoration, then this method will not be accessible to its subclasses (not instances of subclasses), so this method is not possible to override the quilt class, in this sense, private and final at the same time to modify a method is meaningless, But Java does allow you to do so. If you see a method defined in the subclass that has the same name as the final decoration in the parent class, it is certainly not a rewrite, except that it defines a method that looks the same in the subclass, and if you add @override to the subclass, you will report a compilation error.

Iv. use of the final on the class

The final decorated class will not be inherited, and a sealed class in C # is a good idea.

In addition, a local variable must be declared as a final type if the program needs to use a local variable in an anonymous inner class or a normal inner class. Otherwise, an error is compiled. Why must it be declared as a final type? This is because for ordinary variables, its scope is to stay within the method, when the method execution ends, the local variable disappears, but the inner class may produce an implicit "closure", the closure of the local variable out of the way it continues to exist. Look at the following example:

 Public classClosuretest { Public Static voidMain (string[] args) {FinalString str = "Java";//Defining local VariablesNewThread (NewRunnable () { Public voidrun () { for(inti=0; i<100; i++) {System.out.println (str+i);Try{Thread.Sleep (100) ;} Catch(interruptedexception e) {e.printstacktrace ();}}}). Start ();} }

The program first defines a local variable str, when the program Main method execution is completed, the life cycle of STR is finished, but the child thread has not executed the end, and the child thread to use the local variable str in main, this time expanded the scope of Str. At this point, if STR is not modified to be the final type and can be arbitrarily changed, it will cause great confusion, so the Java compiler requires that all local variables accessed by the inner class must be decorated with the final modifier.

Finally, this paper deeply analyzes the function of final modifier in Java, it seems that the simple behind, in fact, contains a lot of important truth. Learning a technology is not limited to the use of the surface, the master is often standing in the understanding and even reconstruction of the level, the road long its repair far, I will go up and down and quest.

Final modifiers in Java in-depth study

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.