String detailed explanation

It can be seen from the source code that the String class is modified by the keyword final. Before understanding String, let's first introduce the final keyword

1: Final modified member variables must be initialized when they are first defined or in the constructor. If you modify a local variable, you don't need to initialize it when you define it (of course, it won't matter to you when you define it), you can initialize it before use. No matter whether it is a member variable or a local variable, it cannot be changed after initialization, otherwise a compilation error will be reported!

For a final variable, if it is a variable of primitive data type, its value cannot be changed once it is initialized; if it is a variable of reference type, it cannot be allowed to point to another object after it is initialized.

After a reference variable is final modified, although it can no longer point to other objects, the content of the object it points to is mutable.

When using final to act on member variables of a class, member variables (note that they are member variables of a class, local variables only need to be initialized and assigned before use) must be initialized and assigned at the time of definition or in the constructor, and final variables Once initialized and assigned, it cannot be assigned again. And assign an initial value to this variable in all constructors of the class where the variable is located

When final and static modify a member variable at the same time, it must be initialized when it is defined.

Note: The initialization here can also be the value returned after calling a method, not necessarily a specific value.

2: When a class is modified with final, it indicates that the class cannot be inherited. In other words, if a class you will never let him be inherited, you can use final to modify it. Member variables in final classes can be made final as needed, but it should be noted that all member methods in final classes are implicitly designated as final methods.

3: "There are two reasons to use final methods. The first reason is to lock the method in case any inheriting class modifies its meaning; the second reason is efficiency. In earlier Java implementations, final methods were Switch to inline calls. But if the method is too large, you may not see any performance gains from inline calls. In recent Java versions, there is no need to use final methods for these optimizations.”

       Therefore, make a method final only if you want to explicitly prohibit the method from being overridden in subclasses.

  Note: private methods of a class are implicitly designated as final methods.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326273684&siteId=291194637