Final keyword

1. Overview

The most common meaning is to declare that "this thing cannot be changed". The reason for banning change may be to consider two factors: design or efficiency. Final keyword can be used to modify variables, methods and classes. Modified variables mean that variables cannot be modified, modified methods mean that methods cannot be overridden, and modified classes mean that classes cannot be inherited.

Constant data is useful for two reasons.

2. Modifier variable

When final is applied to an object reference rather than to the original type, its meaning is a little confusing. For primitive types, final makes the value constant, while for object references, final makes the reference constant. Once a reference is initialized to point to one object, it cannot be changed to point to another object. However, objects themselves can be modified, and Java does not provide a way to make any object constant. A demo is as follows:

Because the attribute of something is final, it cannot be assumed that its value can be known at compile time. I4 and i5 prove this. They use randomly generated numbers during runtime. This part of the example also reveals the difference between setting the final value to static and non static. Remember that the static local variable is initialized when the module in which it is located runs for the first time and is operated only once.

Note that final static primitive types with constant initial values (i.e. compile time constants) are all named in uppercase letters, and words are separated by underscores. A field that is both static and final occupies only one storage space that cannot be changed.

Java forces us to assign values to final -- either when defining fields or in each builder. This ensures that the final field is properly initialized before use.

4. Modifier class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>