Using final keyword to Prevent Overriding in Java

Java 8Object Oriented ProgrammingProgramming

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:


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();

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: error: print() in B cannot override print() in A
Published on 12-Feb-2019 15:00:04