How do you prevent a method from getting overridden in java?

Java 8Object Oriented ProgrammingProgramming

Inheritance can be defined as the process where one (parent/super) class acquires the members (methods and fields) of another (child/sub).

If two classes are related to each other with inheritance. If the super class and sub class contains same methods (same name and arguments), When we invoke this it using the sub class object, the method of the sub class will be executed. This mechanism is known as overriding.

Overriding final methods

Once you declare a method final it cannot be overridden If you try to do so, it generates a compile time error −

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 −

Therefore, if you want to prevent a method from being overridden you just need to declare it final.

raja
Published on 01-Aug-2019 15:30:08
Advertisements