In Java, the final keyword is used to define an entity that can only be assigned once. The final keyword can be used in multiple contexts:
- Final variable (Create constant variable)
- Final method (Prevent method overriding)
- Final class (Prevent inheritance)
Final variable
When a variable is declared with the final
keyword, it means the value cannot be changed once it is initialised (it is a constant). Final variable names are normally declared in all cpas.
Note
A final variable must be initialised when it is declared, in the constructor (for instance variables), or in a static block (for static variables).
Initialise upon declaration
public class Example {
static final int CONSTANT_VALUE = 100;
public static void main(String[] args) {
// Compilation Error: cannot assign a value to final variable
// CONSTANT_VALUE = 200;
System.out.println(CONSTANT_VALUE);
}
}
100
Initialise in constructor
public class Example {
final int instanceVar;
public Example(int value) {
this.instanceVar = value;
}
public static void main(String[] args) {
Example myExample = new Example(200);
System.out.println(myExample.instanceVar);
}
}
200
Initialise in static block Learn more about static block on Static block.
public class Example {
static final int staticVar;
static {
staticVar = 300;
}
public static void main(String[] args) {
System.out.println(Example.staticVar);
}
}
300
Final method
When a method is declared with the final
keyword, the method cannot be overridden by subclasses.
public class Example {
public final void display() {
System.out.println("This is the example");
}
}
public class SubExample extends Example {
@Override
public final void display() {
System.out.println("This is the sub example");
}
public static void main(String[] args) {
SubExample subExample = new SubExample();
subExample.display();
}
}
Compile Time Error
Final class
When a class is declared with the final
keyword, the class cannot be extended.
Note
Final methods from parent classes can be inherited, but they cannot be overridden.
public class Example {
//class body
}
// cannot extend the final class !
public class SubExample extends Example {
//class body
}
Compile Time Error
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_Development Programming_Languages Java Final_Keyword Final_Class Final_Method Final_Variable
Reference: