Java final Keyword - Declaring Constants
final Keyword
In a Java program, final means that something cannot be modified because it has been declared as final. In other words, an element given final cannot be modified after initialization.
final can be applied to variables, methods, and classes, and its function differs depending on where it is declared.
| Declaration location | Description |
|---|---|
| Variable | Used to make variable data constant, making the value impossible to change. |
| Method | Overriding becomes impossible. |
| Class | Inheritance becomes impossible. |
final Variables
final dataType variableName = value;
When final is applied, a variable becomes a constant. A constant means a value that does not change, and a variable declared as a constant cannot have its value changed.
By convention, constant names are declared with uppercase English letters and underscores (_). This rule is not a syntax rule, but following common naming conventions is also important for code readability. For example, the following declares a string constant named GREETING_MSG.
final String GREETING_MSG = "Hello World! Java.";
final Object Variables
For object variables, fields can be changed, but a new object cannot be created and assigned to the object variable.
class SampleClass {
int a;
}
public final class FinalSample {
public static void main(String[] args) {
final int RESULT = 10;
RESULT++;
final SampleClass SAMPLE = new SampleClass();
SAMPLE.a = 10;
SAMPLE.a = 15;
SAMPLE = new SampleClass(); // A new object cannot be created and assigned.
}
}
final Global Variables
Usually, a combination of the final and static keywords is used for global variables to define fixed values shared in multiple places.
public class FinalSample {
final int INDEX_LIMIT = 100;
public void display() {
System.out.println(INDEX_LIMIT);
int[] arr = new int[INDEX_LIMIT];
INDEX_LIMIT = 1005; // Error: the value cannot be reassigned.
}
}
final Arguments
Arguments can also be declared as final. Once declared, the argument cannot be reassigned inside the method where it is used.
public final class FinalSample {
public void finalTestMethod(final int a) {
a = 10; // Error: the value cannot be reassigned.
}
}
final Methods
A final method cannot be redefined, or overridden, in an inherited child class.
class FinalMethodTest {
int result = 10;
public final void printResult() {
System.out.println(result);
}
}
public class ExampleClass extends FinalMethodTest {
@Override
public final void printResult() { // Error: overriding is not possible.
}
}
final Classes
If a class is written with final, it cannot be inherited. final is used on classes whose behavior would not work correctly if variables or methods were redefined.
final class ExtendTest {
int a;
}
public class ExampleClass extends ExtendTest { // Error: ExtendTest cannot be inherited.
public static void main(String[] args) {
}
}