New Delhi, India
minigranth@gmail.com

Final Keyword In Java

Created with Sketch.

Core Java Tutorial

[fblike]

Final Keyword In Java : Introduction

  • Java final keyword is used as prevention, i.e. it restricts user.
  • Java final keyword has three uses :
    1. It can be used with variables to prevent their values from being changed.
    2. It can be used to prevent overriding.
    3. It can be used to prevent inheritance.

 

Final Keyword In Java : The Discussion

1) final with Variables

  • If any variable is made final , it restricts the user to changes its value i.e. the content of variable cannot be changed.

 

Note :  A blank variable can also be declared as final and it will be initialized in constructor only, because constructor are invoked as soon as object of that class is created.

 

Example

 

This image describes the sample program supporting the concept of final keyword with variable.

Final With Variable : Example

 

Output

 

This image describes the output of sample program supporting the concept of final keyword with variable.

Final With Variable : Output

 

  • We tried to change the final variable and compiler throws an error which is stated in output.

 

2) final with Method

  • The only purpose of using final with method is to prevent method overriding.
  • When a method is declared as final then it cannot be overridden. If we try to do so , we get a compile time error. Let us understand with an example.

 

Example

 

This image describes the sample program supporting the concept of final keyword with method.

Final With Method : Example

 

Output

 

This image describes the output of sample program supporting the concept of final keyword with method.

Final With Method : Output

 

  • We tried to override a final method and got an error.

 

3) final with Class        

  • A class preceded with final keyword cannot be inherited.
  • Final keyword prevents a class from getting inherited and also implicitly declares all of its methods as final.

 

Example

 

This image describes the sample program supporting the concept of final keyword with class.

Final With Class : Example

 

Output

 

This image describes the output of sample program supporting the concept of final keyword with class.

Final With Class : Output