Friday, September 26, 2025
HomeLanguagesJavaPrivate and final methods in Java

Private and final methods in Java

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.

RELATED ARTICLES

Most Popular

Dominic
32321 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6690 POSTS0 COMMENTS
Nicole Veronica
11857 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11912 POSTS0 COMMENTS
Shaida Kate Naidoo
6802 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6761 POSTS0 COMMENTS
Umr Jansen
6768 POSTS0 COMMENTS