Final Keyword In Java

Final Keyword In Java

Final keyword is used while declaring an entity in java, the entity are classes, variables, methods. if there entities are declared with the final keyword then they cant modified again in the program

Final variables

Once we declare a variable using final, the variable cannot be re modified again in the program,the final variable has a constant value throught the program

Syntax

final data_type variable_name = value;

Example

final double pi=3.14;

Example program

class maths{
final double pi=3.14;
void change(){
pi=50;
}
public static void main(String args[]){
maths obj=new maths();
obj.change();
}
}

Output

(Error)maths.java:4: error: cannot assign a value to final variable pi
pi=50;
^

In the above example program pi data member in a maths class is declare as a 3.14,so now you cannot change the value of the variable again in the program

Blank final variable

A final variable can be declared with any initialization of the value,but we must intialize a value for the final variable in the constructer of that class

Example

class maths{
final double pi;
maths(){
pi=3.14;
}
public static void main(String args[]){
maths obj=new maths();
System.out.println("Pi value is"+obj.pi);
}
}

Output

Pi value is3.14

if we didnt initalize the value for the final varibale in the constructer class, program throws a compilation error ,as below

Output (Error)maths.java:5: error: variable pi might not have been initialized
}
^

Java final Method

if we declare a method with a final keyword, a child class can access the method but child class method with the same name cannot override the final method

Syntax

final return_type method(){
//statements
}

Example

class maths{
double pi=3.14;
final void show(){
System.out.println("Pi value is (parent class method)"+pi);
}
}
class maths2 extends maths{
void show(){
System.out.println("Pi value is (child method)"+pi);
}
public static void main(String args[]){
maths2 obj=new maths2();
obj.show();
}
}

Output

(error)maths2.java:9: error: show() in maths2 cannot override show() in maths
void show(){
^
overridden method is final

In the above program show( ) from a child class (maths2), the class cannot be override Show( ) in the parent class (maths), because of the final keyword.

Java final class

If we declare a class using a final keyword ,then the class cannot be inherited for creating child class

Syntax

final class ClassName{
//statements
}

Example

final class maths{
double pi=3.14;
}
class maths2 extends maths{
void show(){
System.out.println("Pi value is "+pi);
}
public static void main(String args[]){
maths2 obj=new maths2();
obj.show();
}
}

Output

(Error)maths2.java:6: error: cannot inherit from final maths
class maths2 extends maths{
^

In the above example maths(child class ) cannot be created because of final keyword. so maths2 cannot extend maths

Last updated on by vishal devxo