In Java, the final
access modifier is used to restrict the usage of variables, methods, and classes in various ways. When something is declared as final
, it means its value or behavior cannot be changed after initialization or declaration.
Uses of final
in Java:
- Final Variables:
- A
final
variable is a constant. Once it is assigned a value, it cannot be reassigned. - If a
final
variable is not initialized at the time of declaration, it must be initialized in the constructor or an initializer block.
Example:
```java
public class Example {
final int MAX_VALUE \= 100;
void display() { // MAX_VALUE = 200; // This will cause a compilation error System.out.println("Max Value: " + MAX_VALUE); }
}
```
- Final Methods:
- A
final
method cannot be overridden by subclasses. This ensures that the method’s behavior remains consistent across all subclasses.
Example:
```java
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// void display() { } // This will cause a compilation error
}
```
- Final Classes:
- A
final
class cannot be subclassed. This is useful when you want to prevent inheritance, ensuring that the class’s implementation cannot be altered.
Example:
```java
final class Utility {
void performAction() {
System.out.println("Performing action.");
}
}
// class ExtendedUtility extends Utility { } // This will cause a compilation error
```
Follow-up Question
- What happens if you try to reassign a
final
variable in Java? - Answer: If you try to reassign a
final
variable, the Java compiler will throw a compilation error, as the value of afinal
variable cannot be changed once it has been initialized.