Skip to content

Final Keyword in java

Reading Time: < 1 minute

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

  1. variable
  2. method
  3. class

1.If a variable is declared as final in java,you cannot change the value of final variable.i.e it will be constant.

2.Example for final variable :

final int speed=90;

this speed value cannot be changed at any time.

3.Final methods cannot be overriden.i.e if a method is declared as final it can be defined only once.It cannot be redefined.Final methods can be inherited but cannot be overriden.

4.Example for final method :

final void run(){System.out.println(“running”);}

so here run method has been defined and it prints the output to the console as running.Hereafter You cannot redefine the run method anywhere in your code once it has been declared as final.

5.Final Class.if a class is declared as final.It cannot be extended.It means a class declared as final cannot be inherited.

6.Syntax for final class:

final class  Bike{}

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can’t be changed because final variable once assigned a value can never be changed.


class Bike9{
final int speedlimit=90;//final variablevoid run(){speedlimit=400;}public static void main(String args[]){

Bike9 obj=new  Bike9();

obj.run();

}

}//end of class

Output:Compile Time Error

 

Java final method

If you make any method as final, you cannot override it.

Example of final method

class Bike{

See also  Laravel Where Condition Based On A Relationship Table

final void run(){System.out.println(“running”);}

}

class Honda extends Bike{

void run(){System.out.println(“running safely with 100kmph”);}

public static void main(String args[]){

Honda honda= new Honda();

honda.run();

}

}

Output:Compile Time Error
Tags:

Leave a Reply