What is a final method in Java?

Java 8Object Oriented ProgrammingProgramming

The final modifier for finalizing the implementations of classes, methods, and variables.

We can declare a method as final, once you declare a method final it cannot be overridden. So, you cannot modify a final method from a sub class.

The main intention of making a method final would be that the content of the method should not be changed by any outsider.

Example

public class FinalMethodExample {
   public final void display(){
      System.out.println("Hello welcome to Tutorialspoint");
   }
   public static void main(String args[]){
      new FinalMethodExample().display();
   }
   class Sample extends FinalMethodExample{
      public void display(){
         System.out.println("hi");
      }
   }
}

Output

FinalMethodExample.java:12: error: display() in FinalMethodExample.Sample cannot override display() in FinalMethodExample
public void display(){
            ^
overridden method is final
1 error
raja
Published on 08-Jan-2018 11:54:11
Advertisements