[several uses of the Java]final keyword

Source: Internet
Author: User

In the Java keyword,static and final are two of the keywords we have to master. Unlike other keywords, they are used in a variety of ways, and can improve the performance of the program and optimize the structure of the program in a certain environment. Let's look at the final keyword and how to use it.

Final keyword

In Java, the final meaning is slightly different from one scenario to another, but in general it refers to " this is immutable ". Below, let's talk about the Final four main uses.

1. Retouching data

When writing a program, we often need to explain that a data is immutable and we become constants. In Java, a variable modified with the final keyword can only be assigned once, and its value cannot be changed during the lifetime. More importantly, final will tell the compiler that this data will not be modified, so the compiler may be able to replace the data or even perform calculations at compile time, which can optimize our program. However, there are subtle differences in the effect of the final keyword when it comes to basic types and reference types. Let's take a look at the following example:

1 classValue {2     intv;3      PublicValue (intv) {4          This. v =v;5     }6 }7 8  Public classFinaltest {9     Ten     Final intF1 = 1; One     Final intF2; A      Publicfinaltest () { -F2 = 2; -     } the  -      Public Static voidMain (string[] args) { -         Final intvalue1 = 1; -         //value1 = 4; +         Final Doublevalue2; -value2 = 2.0; +         FinalValue Value3 =NewValue (1); AVALUE3.V = 4; at     } -}

In the example above, let's take a look at some of the final modified data in the main method, after assigning the initial value to value1, we can no longer modify the value of value1, the final keyword plays a constant role. From value2 we can see that the final modified variable can not be assigned a value at the time of Declaration, that is, it can be declared first and then assigned. Value3 a reference variable, here we can see the final modified reference variable, only to qualify the reference variable reference cannot be changed, that is, you cannot refer to another value object again, but the value of the referenced object can be changed, from the memory model we see more clearly:

, the final decorated value is represented by a thick border that its value is immutable, and we know that the value of the reference variable is actually the address of the object it refers to, meaning that the value of the address is immutable, which explains why the reference variable cannot be changed by the reference object. The actual referenced object is actually not affected by the final keyword, so its value can be changed.

On the other hand, we see the slight difference in the final modification of member variables, because the value of the final modified data is immutable, so we have to make sure that the member variable is already assigned before it is used. So for a final modified member variable, we have and only two places to assign it, one to declare the member and the other to assign it in the constructor, and in these two places we have to give them an initial value.

Finally, one thing to note is that members using both static and final adornments occupy only a certain amount of storage space that cannot be changed in memory.

2. Modification method Parameters

As we can see earlier, if the variable is created by ourselves, then using the final decoration means that we will only assign it a value once and not change the value of the variable. So if the variable is passed in as a parameter, how do we guarantee that its value will not change? This is the second use of final, that is, when we write a method, we can add the final keyword before the parameter, which means that in the entire method, we don't (actually can't) change the value of the parameter:

 Public class finaltest {    /**    /publicvoid Finalfunc (final  intfinal  value value) {        //  i = 5; Cannot change the value        of I // v = new value (), cannot change the value        of V // You can change the value of a reference object     }}
3. Modification methods

The third way, the final keyword decoration method, indicates that the method cannot be overwritten. This use is mainly from the design perspective, that is, explicitly tell other programmers who might inherit the class, do not want them to overwrite this method. This approach is easy to understand, however, there is a little connection between the private and final keywords, which is that all private methods in the class are implicitly specified as final and cannot be overwritten because the private method cannot be used outside the class.

4. Modifier class

Knowing the other uses of the final keyword, it is easy to think of the effect of using the final keyword to decorate the class, which is that a final decorated class cannot be inherited.

We have explained the Final four usages, but we seldom use them for the third and fourth uses. This is not unreasonable, from the final design, these two usages can even be said to be a chicken, because for developers, if we write a class is inherited more, it means that the class we write more valuable, the more successful. Even from a design standpoint, it is not necessary to design a class to be non-inheritable. The Java standard Library is a good example, especially in Java 1.0/1.1, where vector classes are so widely used that it may be more useful if none of the methods are specified as final. For such useful classes, it is easy to think of inheriting and rewriting them, however, due to the final effect, we have been hindered by the expansion of the Vector class, which has caused the vector to not fully realize its full value.

Summarize

The final keyword is one of the keywords that we use a lot, but not every usage is worth our extensive use. Its main uses are the following four types:

    1. Used to modify data, including member variables and local variables, which can only be assigned once and whose values cannot be changed. For a member variable, we must assign a value to it either at declaration time or in the constructor method;
    2. Used to modify a method parameter to indicate that its value cannot be changed during the lifetime of the variable;
    3. A modification method that indicates that the method cannot be overridden;
    4. Modifies the class to indicate that the class cannot be inherited.

Of the four methods above, the third and fourth methods need to be used with caution, because in most cases we do not need to use final to decorate methods and classes, if only for the sake of design considerations.

[several uses of the Java]final keyword

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.