Use of Final Keyword in Java

In this class, We discuss the Use of Final Keyword in Java.

The reader should have prior knowledge of object-oriented programming concepts. Click Here.

The final keyword is used in three situations.

1) To declare constants

2) To restrict method overriding

3) To restrict inheritance

We take examples and understand all three concepts.

Example:

The below diagram shows the example program for constants.

class A

{

final int q = 20;

int p = 30;

void add()

{

int c;

c = p+q;

System.out.println(c);

}

}

class test

{

public static void main(String args[])

{

A ob = new A();

ob.q=30; // This statement is not allowed – compilation error

}

}

In the above example, variable q is declared “final.”

The variable q acts as a constant.

We can use the value present in q, but we can not modify the value.

The modification of variable q is not allowed.

Constant modification is identified during compilation.

Example 2:

class A

{

int q = 20;

int p = 30;

final void add()

{

int c;

c = p+q;

System.out.println(c);

}

}

Class B extends A

{

void add()

{

}

}

class test

{

public static void main(String args[])

{

A ob = new A();

ob.q=30;

}

}

In the above example, add method is declared “final.”

The add method is not allowed to override in class “B.”

Overriding is identified during compilation.

Example 3:

final class A

{

int q = 20;

int p = 30;

void add()

{

int c;

c = p+q;

System.out.println(c);

}

}

Class B extends A //not allowed.

{

void add1()

{

}

}

class test

{

public static void main(String args[])

{

A ob = new A();

ob.q=30;

}

}

The above example class “A” is declared final.

The class A is not allowed to inherit.