Why use the final method

Source: Internet
Author: User

The final method may be used for two reasons. The first is to "lock" the method to prevent any inherited class from changing its original meaning. When designing a program, you can do this if you want the behavior of a method to remain unchanged during inheritance, and cannot be overwritten or rewritten.

The second reason to adopt the final approach is the efficiency of program execution. When a method is final, the compiler can place all calls to that method into an "embedded" call. Whenever the compiler discovers a final method call, ignores the usual code insertion method (which is based on its own judgment) for executing the method invocation mechanism (pressing the argument onto the stack; jumping to the method code and executing it; jumping back; clearing the stack's arguments; and finally processing the return value). Instead, it replaces the method invocation with a copy of the actual code within the method body. Doing so avoids the overhead of the method invocation. Of course, if the method is too large, then the program will become very swollen, and may be less than the embedded code to bring any performance improvement. Because any ascension is offset by the time spent within the method. The Java compiler automatically detects these situations and is quite "sensible" in deciding whether to embed a final method. However, it is best not to fully believe that the compiler can make all the judgments correctly. Typically, you should consider setting a method to final only if the method has very little code, or if you want to explicitly prohibit the method from being overwritten.

All private methods within a class are automatically final. Since we do not have access to a private method, it is never overwritten by other methods (if forced to do so, the compiler will give a false hint). You can add a final indicator to a private method, but you cannot provide any additional meaning for that method.

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.