Parsing the various uses of the final keyword in Java

Source: Internet
Author: User
Tags value of pi

First, we can literally understand the Chinese meaning of the final English word: " final, final, decisive; non-changing;". Obviously, if the final keyword is interpreted in Chinese, "immutable" is more appropriate. When you are writing a program, you may encounter situations where I want to define a variable that can be initialized, but it cannot be changed.

For example, I now want to define a variable to hold the value of pi, as an objective, correct and guaranteed value, if you change it in a post-process program, it can result in errors or even a program crash. Then the final keyword will be useful at this time. However, final can not only be used to modify the value, it has other uses, see the following examples should have a basic understanding.

If there is any mistake, please criticize it.

1. Use final to decorate the data

1.1 Use Final to modify the value:

Example 1
publicclass demo{ publicstaticvoid Main (String[]args) { finaldouble pi=3.14; System.out.println (PI); PI=3.1; System.out.println (PI);} }

As shown in Example 1, what happens if the final modified variable pi is modified?

Well, compilation doesn't pass, which means that the final modified numeric variables cannot be changed.

Now there is another question, if the final definition of the variable, not initialized, will not error? See Example 2:

Example 2
publicclass demo{ publicstaticvoid Main (String[]args) { Final Double PI; System.out.println (PI);} }

Still will error, in fact this and FINA's relationship is not big, just because no assignment, even if not final, will also error (pro-test).

1.2 What is the value above, if the final decoration is an object?

//Example 3
Public classdemo{ Public Static voidMain (String[]args) {FinalCat cat1=NewCat (1); Cat Cat2=NewCat (2); CAT1=Cat2; }}classcat{Private intId=0; Private intAge=0; Cat (intID) { This. id=ID;} Public voidSetage (intAge ) { This. age=Age ; }}

The compilation still does not pass.

But CAT1 grew up a year old, I want to change his age, can you, put a test code:

//Example 4
Public classdemo{ Public Static voidMain (String[]args) {FinalCat cat1=NewCat (1); //Cat Cat2=new Cat (2);Cat1.setage (1); System.out.println (Cat1.getage ()); }}classcat{Private intId=0; Private intAge=0; Cat (intID) { This. id=ID;} Public voidSetage (intAge ) { This. age=Age ; } Public intGetage () {returnAge ; }}

Operation Result:

Compile and run without any obstacles. What does it mean? When you use final to decorate an object, you cannot change the object's reference, but you can modify the object's property values. CAT1 can only point to a cat with an ID of 1, and if it points to a cat referred to by CAT2, the compiler will report an error (example 3).

1.3 Using final to modify parameters

When final modifies the formal parameter, the formal parameter cannot be changed, for example, when I get the age, I secretly change the ID:

 Public classdemo{ Public Static voidMain (String[]args) {Cat cat1=NewCat (1); System.out.println (Cat1.getage (1)); }}classcat{Private intId=0; Private intAge=0; Cat (intID) { This. id=ID;}  Public voidSetage (intAge ) {         This. age=Age ; }     Public intGetage (Final intID) {ID++; return  This. Age; }}

Sure enough, the error!

2.final modification Method (function)

The purpose of the final modification method is to lock the method and prevent inheriting its class from modifying (overwriting) it. For example, Cat class is an animal, so it inherits the animal animal, but every animal has the stipulation: cannot harm the human, therefore animal's rule method uses the final modification, does not allow the successor to modify, the code is as follows:

 Public classdemo{ Public Static voidMain (String[]args) {Cat cat1=NewCat (1);        Cat1.rule (); //System.out.println (Cat1.getage ());     }}classanimal{ Public Final voidrule () {System.out.println ("Do not hurt people!"); }}classCatextendsanimal{Private intId=0; Private intAge=0; Cat (intID) { This. id=ID;}  Public voidSetage (intAge ) {         This. age=Age ; }     Public intGetage () {returnAge ; }     Public Final voidrule () {System.out.println ("I want to Hurt people!"); }}

I failed when I tried to overwrite the base class method. Of course, the example is the public modification of the method, but if it is the private decoration method, the child itself is not visible, let alone overwrite.

3. Use final to modify the class:

When the class is decorated with final, it means that the class is not intended to be inherited from the beginning of the design, in other words, it does not allow others to inherit the class, thus guaranteeing security. For example, I put a final in front of the animal class.

The error in compiling the report is clear: Cannot be inherited.

The difference between 4.final and static

The final modification is mainly for the performance of "non-modifiable", thus improving security. The static focus is on sharing and convenience. Creating a static decorated function in a class can be accessed directly from the class name, the new object of the class, or the shared property of the static modifier.

The specific use of static, can be referred to: http://www.cnblogs.com/dolphin0520/p/3799052.html.

Parsing the various uses of the final keyword in Java

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.