Make private methods final?

痞子三分冷 提交于 2019-11-28 06:09:57

Adding final to methods does not improve performance with Sun HotSpot. Where final could be added, HotSpot will notice that the method is never overridden and so treat it the same.

In Java private methods are non-virtual. You can't override them, even using nested classes where they may be accessible to subclasses. For instance methods the instructoin to call privates is different from that used for non-privates. Adding final to private methods makes no odds.

As ever, these sort of micro-optimisations are not worth spending time on.

private static Result doSomething(), if this method is not using any instance variables. In any case making them final makes no sense since the accessor is private.

No. It will not. private methods are not inherited. So making them final is a moot point. Also note that you should not make methods final for performance. JVM is smarter than that. This kind of optimization is not much useful. You should make things final, private, private, protected, private, etc based on the semantics and design.

Marking a private method as final does not change anything but it might confuse junior developers looking at your code. Keep it simple.

Doug Porter

The IBM Developer works: Java theory and practice: Is that your final answer? article is an oldie but goodie about using the final keyword in Java:

By making method final we can not override the method. Since Private methods cant be accessed outside the class. There is no sence of making the method final and private. It may hit the performance.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!