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

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 27-Jun-2019 12:31:17
Advertisements