Using final keyword to Prevent Overriding in Java


Method overriding can be prevented by using the final keyword with a method. In other words, a final method cannot be overridden.

A program that demonstrates this is given as follows:

Example

class A {
   int a = 8;
   final void print() {
      System.out.println("Value of a: " + a);
   }
}
class B extends A {
   int b = 3;
   void print() {
      System.out.println("Value of b: " + b);
   }
}
public class Demo {
   public static void main(String args[]) {
      B obj = new B();
      obj.print();
   }
}

The above program generates an error as the method print() in class A is final and so it cannot be overridden by the method print() in class B. The error message is as follows:

Demo.java:15: error: print() in B cannot override print() in A

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements