The role of the final keyword in JAVA __java

Source: Internet
Author: User

The final effect varies with the type being decorated

1. Attributes or variables in the final modifier class

Regardless of whether the attribute is a basic type or a reference type, the final effect is that the value stored in the variable cannot be changed.

This value, for the basic type, contains the real values in the variable, such as 1, "ABC", and so on.

The reference type variable contains an address, so using the final modifier reference type variable means that the address within it cannot be changed, not that the contents of the object or array to which this address is directed cannot be changed, this must be noted.

For example: one of the attributes in the class is the final person p=new person ("name"), so you can't reassign the P, but you can change the value of the attribute in P, p.setname (' newName ');

Final modifier attributes, which can be declared without assigning values, and cannot be modified once assigned. The final attribute can be assigned in three places: when declared, in the initialization block, in the constructor method. Be sure to assign a value anyway.

2. Methods in final Modified class

Function: Can be inherited, but cannot be overridden after inheritance.

3. Final Cosmetic class

Function: A class cannot be inherited.

Think of an interesting phenomenon:

BYTE B1=1;

BYTE b2=3;

Byte b3=b1+b2;//error occurs when the program executes to this line, because B1, B2 can be automatically converted to a variable of type int, which is converted by the Java Virtual machine, resulting in an int assigning to byte-----error

If you add final to B1 B2, it won't go wrong.

Final byte b1=1;

Final byte b2=3;

Byte b3=b1+b2;//can not be wrong, I believe you read the above explanation to know the reason.

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.