Java final method and javafinal Method

Source: Internet
Author: User

Java final method and javafinal Method

The final method may be used for two reasons. The first is to lock the method to prevent any inheritance 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 the inheritance period and cannot be overwritten or rewritten.

The second reason for using the final method is the efficiency of program execution. After a method is set to final, the compiler can put all calls to that method into "embedded" calls. As long as the compiler finds a final method call, it will (based on its own judgment) Ignore the General Code insertion method used to execute the method call mechanism (push the independent variables into the stack; jump to the method code and execute it; jump back; clear the stack independent variable; and finally process the returned value ). Instead, it replaces the method call with a copy of the actual code in the method body. This avoids system overhead during method calls. Of course, if the method size is too large, the program will become swollen and may not be able to achieve any performance improvement caused by embedded code. Because any improvement is offset by the time spent in the method. The Java compiler can automatically detect these situations and "wisely" decide whether to embed a final method. However, it is best not to fully trust the compiler to make all the judgments correctly. Generally, you should consider setting a method as final only when the amount of code for the method is very small or you want to explicitly prohibit the method from being overwritten. All private methods in the class are automatically final. Since we cannot access a private method, it will never be overwritten by other methods (if forced to do so, the compiler will give an error message ). You can add a final indicator for a private method, but 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.