Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make private methods final?

Tags:

java

final

Is it beneficial to make private methods final? Would that improve performance?

I think "private final" doesn't make much sense, because a private method cannot be overridden. So the method lookup should be efficient as when using final.

And would it be better to make a private helper method static (when possible)?

What's best to use?

  private Result doSomething()   private final Result doSomething()   private static Result doSomething()   private static final Result doSomething() 
like image 337
deamon Avatar asked Dec 31 '09 08:12

deamon


People also ask

Can a private method be final?

So, to answer question 2, yes, all compilers will treat private methods as final . The compiler will not allow any private method to be overridden. Likewise, all compilers will prevent subclasses from overriding final methods.

Can we override private and final methods?

No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.

What is the difference between private method and final method?

private is about accessibility like public or protected or no modifier. final is about modification during inheritance. private methods are not just accessible from the outside of the class. final methods can not be overridden by the child class.

Can we use private and final together in Java?

In Java as both private and final methods do not allow the overridden functionality so no use of using both modifiers together with same method.


2 Answers

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.

like image 194
Tom Hawtin - tackline Avatar answered Sep 22 '22 08:09

Tom Hawtin - tackline


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.

like image 43
Binoj Antony Avatar answered Sep 18 '22 08:09

Binoj Antony