Private and final?

Is it necessary to declare a private method final?

Q: Given that:

  • private methods cannot be overridden by subclasses
  • final methods cannot be overridden by subclasses
  • final methods allow for faster code when compiled with optimizations on (javac -O)

My questions are:

  1. Why not declare all private methods final as well?
  2. Do most compilers treat private methods as final?

A: As you point out, subclasses may not override private methods by design. Furthermore, the final keyword tells the compiler that subclasses may not override a method regardless of its access level. Since private already implies that a subclass may not override a method, declaring a private method to be final is redundant. Making the declaration won't cause problems, but it won't accomplish anything either, since privates are automatically considered final.

Well, the practice of declaring all private methods final will have one side effect. Any novice Java programmer who encounters your code will assimilate your usage of private final, thinking that privates must be declared in that manner. So, you'll be able to judge who has and who has not been in contact with your code. It might prove an interesting exercise.

So, to answer question 1, there is no need to declare private members final.

As for question 2, an optimizing compiler and JVM can take advantage of private methods and final methods. Since subclasses may not override those types, there is no need to do dynamic binding at runtime. Subclasses will never override the method, so the runtime will always know what method to call without searching up the inheritance hierarchy. During compilation an optimizing compiler may even choose to inline all private and final methods to improve performance.

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.

A more interesting question: Will all compilers optimize finals and privates so that they are inline? The short answer is no. Optimization behavior will be dependent on the compiler and its settings.

Note: Our discussion of private final only applies to methods. Private final member variables are treated differently

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more