1 Answer
Jai Janardhan

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:

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


We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.