Can we override final methods in Java?

Java 8Object Oriented ProgrammingProgramming

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 −

raja
Published on 05-Jul-2019 14:35:52
Advertisements