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. It may in-fact cause unnecessary confusion.
class Base { private final void foo() {} // The above method foo() is same as following. The keyword // final is redundant in above declaration. // private void foo() {} } |
For example, both ‘program 1’ and ‘program 2’ below produce same compiler error “foo() has private access in Base”.
Program 1
// file name: Main.java class Base { private final void foo() {} } class Derived extends Base { public void foo() {} } public class Main { public static void main(String args[]) { Base b = new Derived(); b.foo(); } } |
Program 2
// file name: Main.java class Base { private void foo() {} } class Derived extends Base { public void foo() {} } public class Main { public static void main(String args[]) { Base b = new Derived(); b.foo(); } } |
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Unreachable statement using final and non-final variable in Java
- Can we override private methods in Java?
- Private Methods in Java 9 Interfaces
- Static methods vs Instance methods in Java
- Private Constructors and Singleton Classes in Java
- Replacing 'public' with 'private' in "main" in Java
- How to call private method from another class in Java with help of Reflection API?
- final, finally and finalize in Java
- Static and non static blank final variables in Java
- Difference between Final and Abstract in Java
- final variables in Java
- Assigning values to static final variables in Java
- Blank Final in Java
- Using final with Inheritance in Java
- final keyword in java
- Instance variable as final in Java
- Final static variable in Java
- Final local variables in Java
- final vs Immutability in Java
- Final arrays in Java

