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

No comments:

Post a comment