Detailed explanation of the use of final keyword in java object-oriented programming

In Java, the final keyword is used to declare that objects are immutable. The objects here include variables, methods and classes, which is similar to the const keyword in C + +. Immutable means that the state of an object cannot be changed after it is created. The final keyword can be used from three perspectives:

If the final variable defines final object a, a can only be initialized once. Once initialized, a's data cannot be modified. If a is a reference type, other objects cannot be re bound. The uninitialized final variable is called blank final. If it is a member variable, it must be initialized or assigned in the constructor. example:

If the final method defines the final method, the method cannot be overloaded. The method designer does not want other related functions to be abnormal due to the overloading of the method. example:

It should be noted that the definition of the final method may not produce the effect of inline, because whether the method is inline depends on the JVM policy rather than the final keyword. It is inaccurate to improve the efficiency of the method through the final design.

Class X defined by final class X cannot be inherited. In Java, the string class is designed as final, which is defined as follows

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
分享
二维码
< <上一篇
下一篇>>