Program to demonstrate the use of 'final' keyword

In Java, the final keyword is used for three purposes:
  1. It is used to declare a variable as a constant.
  2. It is used to prevent method overriding.
  3. It is used to prevent inheritance.
We can declare a variable in any scope to be final. The value of final variable cannot change after it has been initialized. To declare a final variable, we use the final keyword in the variable declaration before the types.
final  type <variable-name> = value;
class A {
 void show() {
  System.out.println("Inside A");

class B extends A {
 final double PI = 3.14;
 int x = 10;
 void show() {
  System.out.println("Inside B");
  x = 20;
  System.out.println("x = "+x);
  System.out.println("PI = "+PI);
 public static void main(String args[]) {
  B objB = new B();;
  A objA = new A();;
C:\>java B
Inside B
x = 20
PI = 3.14
Inside A

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative