What will happen when we try to override final method of the superclass in Java?


Any method that is declared as final in the superclass cannot be overridden by a subclass. If we try to override the final method of super class we will get an error in Java.

Rules for implementing Method Overriding

  • The method declaration should be the same as that of the method that is to be overridden.
  • The class (subclass) should extend another class (superclass), prior to even try overriding.
  • The Sub Class can never override final methods of the Super Class.

Example

Live Demo

class Car {
   public void brake() {
      System.out.println("brake() method of Car");
   }
   public final void accelerate() {
      System.out.println("accelerate() method of Car");
   }
}
public class BenzCar extends Car {
   public static void main(String[] args) {
      BenzCar benz = new BenzCar();
      benz.accelerate();
      benz.brake();
   }
   public void accelerate() {
      System.out.println("accelerate() method of Benz Car");
   }
}

In the above example, if we try to override the final method (accelerate() method) of the superclass. the compiler will throw an error. Hence we do not override the final method of the superclass in Java.

Output

overridden method is final

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements