Why is the String class final?

Before answering this question, I think it is necessary to find out what final is?

First, understand final
1. Final modified class
A class modified by final cannot be inherited, that is, it cannot have its own subclass, otherwise it will report an error during compilation.

2. Final modified method
The method modified by final cannot be overridden, but:
the premise of overriding is that the subclass can inherit this method from the parent class, so when the access permission of the method modified by final in the parent class is private,
Subclasses can override this method.

3. Final modified variables
Final modified variables, whether they are class attributes, object attributes, formal parameters or local variables, need to be initialized.

2. Answering the question
is mainly for the sake of "security" and "efficiency", because:
1. Since the String class cannot be inherited, it will not be modified, which avoids the security risks caused by inheritance;

2. The String class appears frequently in the program. In order to avoid security risks, it is modified with final every time it appears, which will undoubtedly reduce the execution efficiency of the program, so simply set it as final to improve effectiveness;

Guess you like

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