Introduction
While working on a programming language, programmers often have to finalize things that can’t be changed or overridden by someone. They might restrict other classes to inherit classes, limit methods to override, finalize variables, and whatnot.
Programmers use the Final keyword in Java to restrict other entities to override or modify the entity or class declared with the Final keyword.
The Final keyword is a non-access modifier applicable to a method, variable, or class. It restricts entities to modify or override a class. It is used to show that an entity can’t be modified twice. Hence, we can’t override a method, change the value of a variable, or inherit a class once it’s declared with the Final keyword.
Java Final keyword provides more functionality and can be used with classes, variables, fields, methods, and function parameters. Final variables, final methods, and final classes enable us to restrict variables to re-initialize, methods to override, and classes to inherit, respectively. The Final keyword can be primitive and non-primitive data types.
final also has uses beyond creating immutable objects. It can also be used to prevent inheritance or to make a class static. In short, the final keyword is a versatile tool that can be used in a variety of ways.
The following are different contexts where the final is used:
- Variable
- Method
- Class
Characteristics of Final Keyword in Java
In Java, the final
keyword is used to apply restrictions on classes, methods, and variables. Here are its characteristics:
- Final Variables: When applied to a variable, it means that the variable can only be assigned once. Once initialized, its value cannot be changed. This is particularly useful when you want to create constants.
- Final Methods: When applied to a method, it means that the method cannot be overridden by subclasses. This is often used to enforce immutability or security in classes.
- Final Classes: When applied to a class, it means that the class cannot be subclassed. This is often used to prevent modification or extension of certain classes, particularly utility classes.
- Memory Semantics: When a
final
variable is initialized in a constructor, it’s guaranteed to be initialized before any other threads can access the object. This provides a certain level of thread safety in multi-threaded environments. - Compiler Optimization: The
final
keyword can provide hints to the compiler to perform optimizations. For example, it may inline constant values or methods, improving performance. - Security:
final
keyword can be used to prevent certain types of attacks such as Man-in-the-middle attacks by ensuring certain methods or variables cannot be modified.
Java Final Variable
Programmers can create a final variable when they need to create a constant variable, which means after initializing it cannot be modified or updated.
If we try to modify this variable, the compiler will throw an error. The same way they can do with objects but, in this case we can change the property of objects as we only finalize the reference variable of the object.
Final variables can be used with primitive data types (int, float, double, and char) and non-primitive data types (object references).
Different Methods of Using Final Variable
Final Variables as Constants
Declare a final
variable and initialize it with a constant value. Once you initialized the value, its value cannot be changed.
public class FinalExample {
public static final int MAX_VALUE = 100;
public static void main(String[] args) {
// Access the final variable
System.out.println("Maximum value: " + MAX_VALUE);
}
}
JavaOutput
Maximum value: 100
JavaFinal Variables in Methods
Declare method parameters as final
to indicate that the method cannot change their values.
public class FinalMethodExample {
public void printNumber(final int num) {
// num = 10; // This will cause a compilation error
System.out.println("Number: " + num);
}
public static void main(String[] args) {
FinalMethodExample example = new FinalMethodExample();
example.printNumber(5);
}
}
JavaOutput
Number: 5
JavaFinal Variables in Classes
Declare a class as final
to indicate that it cannot be subclassed.
final class FinalClass {
// Class definition
}
// This will cause a compilation error since FinalClass cannot be extended
// class SubClass extends FinalClass { }
JavaOutput
The code defines a final class named FinalClass, indicating that it cannot be subclassed.
Then, it attempts to create a subclass SubClass extending FinalClass, which will result
in a compilation error due to the attempt to extend a final class.
JavaFinal Variables in Instance Fields
Declare instance fields as final
to ensure they can only be initialized once, either during declaration or in the constructor.
public class FinalInstanceFieldExample {
private final int value;
public FinalInstanceFieldExample(int value) {
this.value = value;
}
public void printValue() {
System.out.println("Value: " + value);
}
public static void main(String[] args) {
FinalInstanceFieldExample example = new FinalInstanceFieldExample(10);
example.printValue();
}
}
JavaOutput
Value: 10
JavaJava Final classes
In Java, a final class prevents subclassing. Declaring a class as final means no other class can inherit from it. This ensures that a particular class, often representing a fundamental concept or functionality, cannot be extended or modified.
Example
final class FinalClass {
private final int value;
public FinalClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
JavaOutput
This code defines a final class named FinalClass with a private final instance field value
of type int. The constructor initializes this field with the provided value. There's also
a method getValue() that allows access to the value of this field.
Since there's no main method, the code doesn't have an output by itself. It just defines
a class that can be used elsewhere. If you want to see the output, you'd need to use this
class in another class with a main method and invoke its methods.
JavaJava Final Method
In Java, a final method cannot be overridden by subclasses. When declared as final in a superclass, it means subclasses cannot alter its implementation.
Example
class ParentClass {
// Final method
public final void finalMethod() {
System.out.println("This is a final method in the ParentClass");
}
}
class ChildClass extends ParentClass {
// Uncommenting this method will result in a compilation error
// @Override
// public void finalMethod() {
// System.out.println("This is an overridden final method in the ChildClass");
// }
}
public class FinalMethodExample {
public static void main(String[] args) {
ParentClass parent = new ParentClass();
parent.finalMethod(); // Output: This is a final method in the ParentClass
ChildClass child = new ChildClass();
child.finalMethod(); // Output: This is a final method in the ParentClass
}
}
JavaOutput
This is a final method in the ParentClass
This is a final method in the ParentClass
JavaIn this example, ParentClass
contains a final method finalMethod()
. Attempts to override this method in a subclass like ChildClass
are commented out, as overriding a final method would result in a compilation error. The FinalMethodExample
class demonstrates calling the final method both through an instance of the parent class and an instance of the child class.
Advantages of Final Keyword in Java
The final
keyword in Java offers several advantages:
- Immutability: When applied to variables, the
final
keyword ensures that the variable’s value cannot be changed after initialization. This promotes immutability, which can lead to safer and more predictable code, especially in concurrent or multithreaded environments. - Security: Marking classes, methods, or variables as
final
prevents them from being subclassed, overridden, or reassigned, respectively. This can enhance security by preventing unintended modifications or extensions that could compromise the integrity or behavior of the code. - Performance Optimization: The
final
keyword provides hints to the compiler and runtime environment that certain elements will not change, allowing them to perform optimizations such as inlining or caching. This can lead to improved performance in some cases. - API Design and Contract: Using
final
can serve as a form of documentation and contract, signaling to other developers that a particular class, method, or variable is intended to be used as-is and should not be modified or extended. This can improve code readability and maintainability. - Thread Safety: In multithreaded environments,
final
variables can be safely accessed by multiple threads without the risk of race conditions or unexpected changes in value, as their values are guaranteed to be immutable after initialization. - Compiler Checks: The
final
keyword enables the compiler to perform additional checks and optimizations, such as ensuring thatfinal
variables are initialized before use or thatfinal
methods are not overridden incorrectly. This helps catch errors at compile time rather than runtime.
Overall, the final
keyword in Java provides a powerful mechanism for enhancing code robustness, security, performance, and maintainability by enforcing immutability, preventing unintended modifications, and enabling compiler optimizations.
Conclusion
In conclusion, the Java final
keyword serves as a powerful tool for enforcing constraints and enhancing various aspects of code quality. By marking variables, methods, or classes as final
, developers can promote immutability, prevent unintended modifications, enhance security, facilitate performance optimizations, and improve code readability and maintainability. Whether used to ensure thread safety, document API contracts, or prevent subclassing, the final
keyword contributes to writing more robust, secure, and efficient Java code. Its versatility and impact make it a valuable feature in Java programming, allowing developers to build more reliable and maintainable software systems.
Frequently Asked Questions
final
keyword in Java? The final
keyword in Java is used to declare entities – variables, methods, or classes – that cannot be changed or overridden after initialization or declaration.
final
variable be reassigned in Java? No, once initialized, the value of a final
variable cannot be changed. Attempts to reassign a value to a final
variable will result in a compilation error.
final
method in a subclass? Attempting to override a final
method in a subclass will result in a compilation error. final
methods are meant to be unchangeable and should not be overridden.
final
class in Java? No, a final
class cannot be subclassed. Attempting to extend a final
class will lead to a compilation error.
final
keyword in Java? Using the final
keyword promotes immutability, enhances security by preventing unintended modifications, facilitates performance optimizations, and serves as documentation for API contracts.