If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, the final
keyword is used to declare entities that cannot be changed after initialization. It can be applied to variables, methods, and classes to enforce immutability, prevent method overriding, and prevent class inheritance, respectively.
Final Variables: When applied to a variable, the final
keyword makes it a constant, meaning its value cannot be changed once it is initialized. Final variables must be assigned a value either during declaration or within the constructor of the class.
javaCopy code
public class MyClass {
final int constantValue = 10; // Final variable
public void changeValue() {
// Error: Cannot change the value of a final variable
// constantValue = 20;
}
}
Final Methods: When applied to a method, the final
keyword prevents the method from being overridden by subclasses. This is often used to ensure that certain methods cannot be modified in subclasses, maintaining the intended behavior of the base class method.
javaCopy code
public class BaseClass {
public final void doSomething() {
// Method implementation
}
}
public class SubClass extends BaseClass {
// Error: Cannot override a final method
// public void doSomething() {
// // Modified implementation (Not allowed)
// }
}
Final Classes: When applied to a class, the final
keyword prevents the class from being subclassed (inherited). This is useful when you want to create a class that should not have any subclasses.
javaCopy code
public final class FinalClass {
// Class implementation
}
// Error: Cannot subclass a final class
// public class SubClass extends FinalClass {
// // Subclass implementation (Not allowed)
// }
Benefits of Using final
:
final
ensures that their values remain constant, preventing unexpected changes and reducing bugs.final
keyword allows the compiler to perform optimizations, as it knows the value of the final variable won't change.final
on methods and classes explicitly communicates that they should not be modified or overridden, making the code easier to understand and maintain.Note:
final
, it means the reference cannot be changed, but the object it refers to can still be modified (the state of the object can be changed).final
, it means the reference cannot be changed, but the contents of the array can still be modified.javaCopy code
final int[] arr = {1, 2, 3};
// Error: Cannot change the reference
// arr = new int[]{4, 5, 6};
// But, the contents of the array can be modified
arr[0] = 10; // Valid
Comments: 0