Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why private method can not be final as well?

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?)

like image 461
MightyPork Avatar asked Apr 18 '14 19:04

MightyPork


People also ask

Can we take private methods and final methods as same?

you cannot use private methods outside the class, the final method can be used. you cannot override both private and final methods.

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.

Why are private methods final?

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.

Can private and final methods be overridden?

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.


2 Answers

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.

like image 86
yshavit Avatar answered Oct 06 '22 00:10

yshavit


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

like image 41
jaco0646 Avatar answered Oct 05 '22 23:10

jaco0646