The role of the final keyword in Java

Source: Internet
Author: User

The role of final varies with the modified type.

1. Final modifier class attributes or variables

Whether the attribute is a basic type or a reference type, the final function is to store the "value" in the variable and cannot be changed.

For basic types, the variable contains actual values, such as 1 and "ABC.

The referenced type variable contains an address, so using final to modify the referenced type variable means that the address in it cannot be changed, it does not mean that the content of the object or array pointed to by this address cannot be changed, so pay attention to this.

For example, if an attribute in the class is final person P = new person ("name"), you cannot re-assign a value to P, but you can change the attribute value in P. setname ('newname ');

Final modifies the attribute. When declaring a variable, it can not be assigned a value, and once assigned, it cannot be modified. You can assign values to the final attribute in three places: Declaration, initialization block, and constructor. In short, you must assign values.

2. Methods in the final modifier class

Function: It can be inherited, but cannot be overwritten after inheritance.

3. Final modifier class

Role: the class cannot be inherited.

Think about an interesting phenomenon:

Byte b1 = 1;

Byte b2 = 3;

Byte B3 = b1 + B2; // an error occurs when the program executes this line, because B1 and B2 can be automatically converted to int type variables, during the operation, the Java Virtual Machine converts the value of an int to byte ----- An error occurred.

If you add final to B1 B2, no error will occur.

Final byte b1 = 1;

Final byte b2 = 3;

Byte B3 = b1 + B2; // No error occurs. I believe you will understand the cause after reading the above explanation.

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.