Private and final methods in Java Programming

Java 8Object Oriented ProgrammingProgramming

In Java private methods are the methods having private access modifier and are restricted to be access in the defining class only and are not visible in their child class due to which are not eligible for overridden. However, we can define a method with the same name in the child class and could access in parent class.

Like private methods final methods in Java are the methods having final non-access modifier instead of private and are again restricted to be accessed in the defining class only and are not visible in their child class due to which are not eligible for overridden. The only difference between private and final methods is that in case of final methods we even can't define a method with the same name in child class while in case of private methods we could define.

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.

Example

 Live Demo

public class PrivateFinalMethods {
   private void print() {
      System.out.println("in parent print");
   }
   public static void main(String[] args) {

      PrivateFinalMethods obj = new PrivateFinalMethodsChild();
      obj.print();
      PrivateFinalMethodsChild obj1 = new PrivateFinalMethodsChild();
      obj1.print();
   }
}
class PrivateFinalMethodsChild extends PrivateFinalMethods {
   public void print(){
      System.out.println("in child print method");
   }
}

Output

in parent print
in child print method
raja
Published on 03-Dec-2018 16:13:29
Advertisements