Why Final Class used in Java?


The final keyword is used with a class to create a final class. The final class cannot be inherited and so the final keyword is commonly used with a class to prevent inheritance.

A program that demonstrates a final class in Java is given as follows:

Example

 Live Demo

final class A {
   private int a = 9;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}
public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.printA();
   }
}

Output

Value of a = 9

Now let us understand the above program.

The class A is a final class. This means that it cannot be inherited. It has a private data member a and a method printA() that displays the value of a. A code snippet which demonstrates this is as follows:

final class A {
   private int a = 9;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}

In the main() method in class Demo, an object obj of final class A is created. Then printA() method is called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.printA();
   }
}

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jul-2019

700 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements