The final keyword in Java

Source: Internet
Author: User

Semantics of 1.final:

The semantics of the final modifier in Java are: immutable.

In Java, final can be decorated with: variables, methods, and classes. The variable is immutable, the method cannot be overridden, and the class is not inheritable.

2. Final modifier variables:

When final modifies a member variable, the timing of the initialization is different when the class variable and the instance variable are decorated.

An instance variable can assign an initial value at declaration time, initialization block, constructor;

A class variable can only be initialized in a static initialization block at declaration time.

3. Macro substitution:

The semantics and constants of the final variable are very similar.

However, in some cases, the final variable is replaced with a "constant" at compile time. That is, at compile time, we are able to directly determine the value of the final variable. Even if the value of the final variable is certain constants are obtained by simple operations, it is also possible.

4. Closures (inner Class)

References to other variables in the inner class must be final decorated. Because, we want to make sure that the closure can exist from the life cycle of the main class. Then this requires that these external variables referenced must be constants.

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.