Is it redundant to add private
and final
to a same method?
class SomeClass { //--snip-- private final void doStuff() { // private work here } }
If it's private
, there's no way anyone can override it, right?
Why is it possible to add final
keyword if it has no effect? (or am I missing something?)
you cannot use private methods outside the class, the final method can be used. you cannot override both private and final methods.
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.
When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons. Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn't add any value.
You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it's not accessible there.
Basically, it's allowed because they didn't feel like it's worthwhile to put a special case prohibiting the private
modifier. It's like how you can also declare methods on an interface as public
, or nested classes in an interface as static
, even though those keywords are implied in interfaces. You can also declare final
methods on a final
class, etc.
Java took the stance of not complaining when you add redundant modifiers. They do it consistently.
One edge case that requires a private method to be final is when the SafeVarargs annotation is used. The following code does not compile, because the private method is not final.
@SafeVarargs private void method(List<String>... stringLists) { //TODO a safe varargs operation }
This was fixed in Java 9.
See: java @SafeVarargs why do private methods need to be final
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With