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 the super class, we will get a compile-time error

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.

Final method

A method is declared final when we put the final keyword before it. The final method ensures that method behavior remains unchanged in inheritance. If we don't want a method to be overridden, we declare it as final.

Example

Below is an example to show that the subclass can never override final methods of the superclass:

class Test
{
    final void show()
    {
        System.out.println("1");     
    }
}
public class Tutorialspoint extends Test
{
    void show() // will throw compile time error
    {
        System.out.println("2");
    }
    public static void main(String[] args)
    {
        System.out.println("Main Method");
    }
}

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

Output

Warnings/Errors:
Tutorialspoint.java:10: error: show() in Tutorialspoint cannot override show() in Test
    void show()
         ^
  overridden method is final
1 error
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-09T14:49:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements