Given that:
private methods cannot be overridden by subclassesfinal methods cannot be overridden by subclassesfinal methods allow for faster code when compiled with optimizations on (javac -O)My questions are:
private methods final as well?private methods as final?
You raise interesting questions.
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
NiceBy Anonymous on August 1, 2009, 6:21 pmVery Helpful. Thank you
Reply | Read entire comment
very helpful and good explanation - thx!By Anonymous on February 24, 2009, 8:31 pmvery helpful and good explanation - thx!
Reply | Read entire comment
What about private field variableBy Anonymous on January 28, 2009, 6:47 amWhat about private field variable http://interview-questions-tips-forum.net
Reply | Read entire comment
View all comments