As far as I understand, private methods and final methods are the same. The Java compiler determines the meanings of private methods at compile time. Neither private methods nor final methods can be modified at runtime, and neither can be overridden. These similarities make it seem like private and final methods are the same. Is this true?
Asked
Active
Viewed 254 times
-4
-
http://www.coderanch.com/t/404696/java/java/Difference-Private-Final – AntonH Apr 11 '14 at 19:05
-
stop giving down votes..please.. Please conclude both are same or not..? – Mdhar9e Apr 11 '14 at 19:07
-
1No, they are not the same. The link I provided gives a concrete example to explain. – AntonH Apr 11 '14 at 19:10
-
1this might be a better question if the wording was clearer. do you mean, "are private methods all final as a practical matter?" – Nathan Hughes Apr 11 '14 at 19:15
2 Answers
2
Consider the following example:
class Super {
private void foo(){}
final void bar(){}
}
class Sub extends Super {
private void foo(){}
final void bar(){}
}
You will have no problem having the foo()
method, but you will get compilation issues when trying to compile the bar()
method. This is because the bar()
method cannot be overriden, but the foo()
method is just not visible - so no overriding occurs.
You can see more answers here: Overriding private methods in Java
2
A private method is automatically final and hidden from its derived class. A final class is not hidden from its derived class. Therefore you can make a new class with the same name as the private method such as
class test {
private void works {
}
}
class tester extends test {
private void works {
}
}
but you cannot make a new class with the same name as the final method
/*----------Doesn't Work------------*/
class test {
final void dWorks {
}
}
class tester extends test {
final void dWorks {
}
}
Example and answer here : http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ309_006.htm

apkisbossin
- 336
- 1
- 3
- 16