The final
keyword in Java is used in various contexts to denote constants or to restrict the modification of classes, methods, and variables. Understanding the final
keyword is crucial for writing robust, maintainable, and secure code. Here’s a comprehensive look at its uses and implications.
final
Keywordfinal
for Constants: Use final
for variables that should not change after initialization.final
for Methods Sparingly: While final
methods can prevent unintended method overriding, they also reduce flexibility. Use them when absolutely necessary.final
to make your objects immutable, enhancing thread safety and predictability.final
classes for security-sensitive classes to prevent tampering through subclassing.A final
method cannot be overridden by subclasses. This is useful for preventing modification of core behavior in inheritance hierarchies.
class Parent {
public final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// The following method would cause a compile-time error
// public void display() {
// System.out.println("Trying to override a final method.");
// }
}
public class FinalMethodExample {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
A final
class cannot be subclassed. This is useful for creating immutable classes or security-related classes to prevent inheritance.
xxxxxxxxxx
public final class FinalClassExample {
public void showMessage() {
System.out.println("This is a final class.");
}
}
// The following class would cause a compile-time error
// class Subclass extends FinalClassExample {
// }
public class TestFinalClass {
public static void main(String[] args) {
FinalClassExample example = new FinalClassExample();
example.showMessage();
}
}
A final
parameter means that the parameter cannot be modified within the method. This is useful for ensuring that the parameter values remain unchanged during the method execution.
xxxxxxxxxx
public class FinalParameterExample {
public void display(final int number) {
// The following line would cause a compile-time error
// number = 10;
System.out.println("The number is: " + number);
}
public static void main(String[] args) {
FinalParameterExample example = new FinalParameterExample();
example.display(5);
}
}
For reference variables, final
means that the reference cannot be changed to point to another object. However, the object’s internal state can still be modified.
xxxxxxxxxx
public class FinalReferenceExample {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Allowed: modifying the object
// sb = new StringBuilder("New"); // Not allowed: changing the reference
System.out.println(sb);
}
}
Immutable Classes: Using final
for class fields and methods helps in creating immutable classes. An immutable class is one whose state cannot be changed once it is created. This is often used for security and simplicity in multi-threaded programming.
xxxxxxxxxx
public final class ImmutableExample {
private final String name;
public ImmutableExample(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static void main(String[] args) {
ImmutableExample example = new ImmutableExample("John");
System.out.println("Name: " + example.getName());
}
}
A final
variable can only be initialized once, either via an initializer or an assignment statement. Once initialized, its value cannot be changed.
Final instance variables must be initialized at the time of declaration or within the constructor of the class.
Final static variables are constants and must be initialized at the time of declaration or within a static block.
xxxxxxxxxx
class FinalVariableExample {
final int MAX_VALUE;
public FinalVariableExample(int maxValue) {
this.MAX_VALUE = maxValue; // Initialized within constructor
}
}
class FinalStaticVariableExample {
public static final int MAX_LIMIT = 100; // constant
}
public class PlanetLearning
{
public static void main(String[] args)
{
FinalVariableExample example = new FinalVariableExample(100);
System.out.println("Max Value: " + example.MAX_VALUE);
System.out.println("Max Limit: " + FinalStaticVariableExample.MAX_LIMIT);
}
}
Max Value: 100
Max Limit: 100