The Final keyword in Java allows us to set limitations on accessibility to a code i.e it adds a restriction to access.
The static keyword can be used in the following context :
- Final Variable : to create constants
- Final Method : to prevent method overriding
- Final Class : to prevent inheritance
1. Java final variable
When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. A final variable can be assigned value later, but only once
When to use a final variable :
final variables must be used only for the values that we want to remain constant throughout the execution of program.
Example:
public class FinalVariableClass {
// a final variable direct initialization
final int NUMBEROFITEMS = 5;
// a blank final variable
final int CART_CAPACITY;
// an another blank final variable
final int MINIMUM;
// a final static variable with direct initialization
static final String COMPANY_NAME = "ProgrammerToday";
// a blank final static variable
static final double TEST_CONSTANT;
// instance initializer block for initializing CART_CAPACITY
{
CART_CAPACITY = 10;
}
// static initializer block for initializing TEST_CONSTANT
static{
TEST_CONSTANT = 1.1;
}
// constructor for initializing MINIMUM
// Note that if there are more than one
// constructor, you must initialize MINIMUM
// in them also
public FinalVariableClass()
{
MINIMUM = 1;
}
public static void main(String args[])
{
// re-assigning final variable will throw compile-time error
COMPANY_NAME = "ProgrammerToday_new";
}
}
2. Java final method
A Final method cannot be overridden
In a scenario where you feel that you method should not be overridden. So that it does not change your piece of code.
Example:
class A {
final void display(){
System.out.println("display method of parent class");
}
}
class B extends A{
//'display()' cannot override 'display()' in 'A'; overridden method is final
void display(){
System.out.println("display method of child class");
}
}
3. Java final class
A final class cannot be extended(inherited).
There are 2 uses of making a class final:
Example:
1. Is to prevent inheritance as the final class cannot be extended. e.g : wrapper classes like Integer, Float etc.
final class FinalClass {
}
// The following class is not correct.
class B extends FinalClass
{
// COMPILE-ERROR! Cannot inherit from final 'FinalClass'
}
2. Is to make the class immutable for example like String.
FAQ , Questions and Answers
Q1. Can we initialize blank final variable ? If yes, then How ?
Sol. There are two ways to initialize blank final variable:
- Using constructor
- Using initialization block
Refer to the example above.
Q2. Can we declare a constructor as final ?
Sol. No, because it is never inherited.
Summary
In this article we learnt about Java Final Keyword and its various use cases. We saw it can be used as a variable, method and a class.
Hope you liked the article !