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;
PROGRAM
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();
  objB.show();
  A objA = new A();
  objA.show();
 }
}
OUTPUT
C:\>javac B.java
C:\>java B
Inside B
x = 20
PI = 3.14
Inside A

Comments

Popular posts from this blog

Develop an Android application to display “Hello World!” on screen

Program to design an applet which draws a circle (having color BLUE) inside a triangle (having color YELLOW)

Build a Simple Android App to Display Student Details