Can we override final methods in Java?


Overriding is a one of the mechanisms to achieve polymorphism. This is the case when we have two classes where, one inherits the properties of another using the extends keyword and, these two classes same method including parameters and return type (say, sample).

Since it is inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass.

When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.

Overriding final methods

No, you cannot override final method in java. If you try to do so, it generates a compile time error saying

Example

class Super{
   public final void demo() {
      System.out.println("This is the method of the superclass");
   }
}
class Sub extends Super{
   public final void demo() {
      System.out.println("This is the method of the subclass");
   }
}

Compile time error

Sub.java:7: error: demo() in Sub cannot override demo() in Super
   public final void demo() {
          ^
   overridden method is final
1 error

If you try to compile the same program in eclipse you will get the following error −

Updated on: 30-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements