Saturday 21 March 2015

The final keyword in Java

 This article explains the usage of final keyword with simple example.
  The final keyword in java is used to restrict the user .There are mainly 3 uses of the keyword final.
1)final can be used to define constants.
2)final can be used to prevent inheritance.
3)final can be used to prevent method overriding.

Let us discuss one by one with example
1) final can be used to define constants.

Syntax :
final data_type variable_name=value;



Output:





  In the example the variable a is declared with final i.e constant . If you try to assign a value to the variable it will not accept and will error out. Please refer the below example .



Error:





2)final can be used to prevent inheritance
 

Error:





We have created class FinalConst as final and tried to inherit that class in the class FinalEx.

3)final can be used to prevent method overriding.


Error:





We have tried to override the method FinalDisplay() in child class which is final method in parent class.



No comments: