🌟 Understanding the final Keyword in Java 🌟

🌟 Understanding the final Keyword in Java 🌟

Understanding the final Keyword in Java

The final keyword in Java is a non-access modifier with specific and powerful use cases across classes, methods, and variables. Here's a quick breakdown of its usage:


In Classes

  • Declaring a class as final prevents inheritance.
  • A final class cannot be extended by any other class.

Example:

final class Constants {
    // Class content
}
// The following line will cause a compilation error:
// class ExtendedConstants extends Constants {}
        

In Methods

  • Applying final to a method prevents overriding by subclasses.
  • Note: Overloading is still possible within the same class.

Example:

class Parent {
    final void display() {
        System.out.println("This cannot be overridden.");
    }
}
class Child extends Parent {
    // The following will cause a compilation error:
    // void display() { ... }
}
        

In Variables

  • The final keyword ensures variables cannot be reassigned after initialization: For primitives, the value remains constant. For objects, the reference cannot change, but the object's state can.

Example:

final int MAX_LIMIT = 100; // Constant value
final List<String> items = new ArrayList<>();
items.add("New Item"); // Allowed: Modifying the state of the object
// The following line will cause a compilation error:
// items = new ArrayList<>();
        

Important Note

Using final ensures references stay unchanged, but it does not guarantee immutability. If immutability is required, consider combining final with immutability patterns like creating immutable classes.


Have you used the final keyword in your projects? What are your best practices or challenges? Let’s discuss below!

Omar Atrak

Front End Developer (Vue, Angular)

4mo

Very useful, thank you

Like
Reply

To view or add a comment, sign in

More articles by BenMoussa FaYssal

Insights from the community

Others also viewed

Explore topics