Java Final Keyword | final keyword | Java example

Java Final keyword is used to define a constant variables, methods and classes.We can also consider them to be constants they cannot be modified later once declared and assigned a value.

 

java final variable :

Difference between normal variable and java final variable can be seen through this example.

Consider a String and assign a value to it

String a = "abc";

now we can reassign a value to the above String

a = "def";

 

But in case of final variable we cannot reassign a value once assigned

java final

Usage : 

final variables are used in calculation purpose, where the value is constant and used multiple times like formula, constant values like pi value etc..,

 

final method :

Consider a method without final declaration display()

class Abc {

    void display() {

        System.out.println("Display original message");
    }

}

 

And now extend the class and try to override the method declared in Abc class.

public class TestExample extends Abc{

    public static void main(String args[]) {

        TestExample testExample = new TestExample();
        testExample.display();
    }

    void display(){

        System.out.println("Display duplicate message");  // override
    }

}

 

java final

You can clearly observe that message is overridden.

 

Now try with java final method

class Abc {

    final void display() {

        System.out.println("Display original message");
    }

}

 

java final

Usage : 

final methods can be used where there is a constant block of code to be executed and can’t be altered later on like banking services, emergency, public domain related all services where we can use the method for our requirement but cant change it.

 

java final class :

The same way final for class will restrict the class from further extensions.

 

Normal class

class Abc {
 .
 .
}

can be extended

public class TestExample extends Abc{
 .
}

 

java final class

final class Abc {
  .
  . 
}

 

java final

Usage : 

final class  restricts the user from sub classing them any further like String, Integer, double…. There functionalities are finalized and can be altered later.

 

Show Buttons
Hide Buttons
Read previous post:
Java Enumerations || Enum || Java example

Java Enumerations : When ever you need to use a constants in program we need to implement them using enum....

Close