DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 2 - final Keyword: Classes, Methods, Variables

The final keyword is one of the most important keywords in Java. It is simple to learn but often misunderstood, especially during interviews.

Many beginners think final simply means "cannot be changed." While that's partially true, the actual meaning depends on where it is used.

In Java, the final keyword can be applied to:

  • Classes
  • Methods
  • Variables
  • Method parameters

Each usage has a different purpose.

In this article, you'll learn:

  • What the final keyword is
  • Why Java provides it
  • final methods
  • final classes
  • final variables
  • Common mistakes
  • Interview questions
  • Best practices

What is the final Keyword?

The final keyword is a non-access modifier that restricts modification.

Depending on where it is used:

Applied To Meaning
Class Cannot be inherited
Method Cannot be overridden
Variable Cannot be reassigned
Parameter Cannot be modified inside the method

Think of final as Java's way of saying:

"This should not be changed."


Why Do We Need the final Keyword?

Suppose you're developing an online banking application.

Some operations should never be modified.

For example:

  • Interest calculation logic
  • Security validation
  • Authentication methods

Allowing subclasses to override these methods could introduce security vulnerabilities.

Similarly, constants like the value of π or GST percentage should never change during program execution.

The final keyword helps protect such code.


Syntax

Final Class

final class ClassName {

}
Enter fullscreen mode Exit fullscreen mode

Final Method

public final void methodName() {

}
Enter fullscreen mode Exit fullscreen mode

Final Variable

final int MAX_USERS = 100;
Enter fullscreen mode Exit fullscreen mode

How It Works

               final
                 │
        ┌────────┼────────┐
        │        │        │
        ▼        ▼        ▼
     Class    Method   Variable
        │        │        │
        ▼        ▼        ▼
 No Inheritance No Override No Reassignment
Enter fullscreen mode Exit fullscreen mode

Rule 1: A final Method Cannot Be Overridden

A child class normally inherits all methods from its parent.

However, if a method is declared final, child classes cannot override it.

Basic Example

class Parent {

    public void property() {
        System.out.println("Cash + Gold + Land");
    }

    public final void marriage() {
        System.out.println("Marriage fixed by family");
    }

}
Enter fullscreen mode Exit fullscreen mode
class Child extends Parent {

    @Override
    public void marriage() {
        System.out.println("Love Marriage");
    }

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

marriage() in Child cannot override marriage() in Parent
overridden method is final
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

Step 1

The compiler reads the Parent class.

Step 2

It notices that marriage() is declared as final.

Step 3

The compiler checks the Child class.

Step 4

Since overriding a final method is not allowed, compilation fails.


Why Would We Make a Method final?

Real-world examples include:

  • Authentication
  • Encryption
  • Security checks
  • Validation logic
  • Framework lifecycle methods

Example:

class PaymentService {

    public final void validatePayment() {
        System.out.println("Payment validated");
    }

}
Enter fullscreen mode Exit fullscreen mode

This prevents developers from accidentally changing important business logic.


Rule 2: A final Class Cannot Be Extended

If a class is declared final, no other class can inherit from it.

Example

final class Customer {

}
Enter fullscreen mode Exit fullscreen mode
class PremiumCustomer extends Customer {

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

cannot inherit from final Customer
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

Step 1

The compiler reads Customer.

Step 2

It sees the final modifier.

Step 3

The compiler checks PremiumCustomer.

Step 4

Inheritance is rejected.


Why Make a Class final?

Sometimes you want to prevent inheritance completely.

Examples include:

  • Immutable classes
  • Security-sensitive classes
  • Utility classes

One famous example is String.

String is declared as:

public final class String
Enter fullscreen mode Exit fullscreen mode

This prevents subclasses from changing the behavior of strings, helping maintain immutability and security.


Rule 3: Methods Inside a final Class Are Effectively Final

Since a final class cannot be extended, none of its methods can ever be overridden.

Example:

final class PaymentService {

    public void processPayment() {
        System.out.println("Payment processed");
    }

}
Enter fullscreen mode Exit fullscreen mode

Even though processPayment() isn't explicitly declared final, it cannot be overridden because inheritance itself is impossible.

Important Note

Every method inside a final class is effectively final, whether you declare it or not.


Rule 4: Variables in a final Class Are Not Automatically Final

This is a common interview question.

Consider the following code:

final class ApplicationConfig {

    static int version = 1;

    static {
        version = 2;
    }

}
Enter fullscreen mode Exit fullscreen mode

This code compiles successfully.

Why?

Because the variable itself isn't declared final.

Only the class is final.

Being inside a final class does not make variables final.


Final Variables

A final variable can be assigned only once.

Example

public class Customer {

    public static void main(String[] args) {

        final int customerId = 101;

        System.out.println(customerId);

    }

}
Enter fullscreen mode Exit fullscreen mode

Output

101
Enter fullscreen mode Exit fullscreen mode

Attempting to Reassign

public class Customer {

    public static void main(String[] args) {

        final int customerId = 101;

        customerId = 202;

    }

}
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

cannot assign a value to final variable customerId
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

Step 1

The variable is declared as final.

Step 2

It receives its initial value.

Step 3

Another assignment is attempted.

Step 4

The compiler rejects the reassignment.


Final Reference Variables

This is another favorite interview topic.

final StringBuilder builder = new StringBuilder("Java");

builder.append(" 21");
Enter fullscreen mode Exit fullscreen mode

This is perfectly valid.

Why?

The reference is final, not the object.

You cannot change what builder points to, but you can modify the object's internal state.

However, this is illegal:

builder = new StringBuilder("Spring");
Enter fullscreen mode Exit fullscreen mode

Compile-Time Error

cannot assign a value to final variable builder
Enter fullscreen mode Exit fullscreen mode

Advantages of final

  • Improves security
  • Prevents accidental modification
  • Helps create immutable classes
  • Makes APIs more reliable
  • Makes program behavior predictable

Disadvantages of final

Using final unnecessarily reduces flexibility.

For example:

  • Prevents inheritance
  • Prevents polymorphism
  • Makes testing harder in some scenarios

Therefore, don't use final unless there's a clear reason.


Common Beginner Mistakes

Mistake 1: Overriding a Final Method

Incorrect code:

class Parent {

    public final void display() {

    }

}

class Child extends Parent {

    public void display() {

    }

}
Enter fullscreen mode Exit fullscreen mode

Why It Fails

A final method cannot be overridden.


Mistake 2: Extending a Final Class

final class Customer {

}

class PremiumCustomer extends Customer {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error:

cannot inherit from final Customer
Enter fullscreen mode Exit fullscreen mode

Mistake 3: Thinking Variables Inside a Final Class Are Final

Incorrect assumption:

"Every variable in a final class is automatically final."

This is false.

Variables must be declared with the final keyword individually.


Comparison Table

Feature Final Class Final Method Final Variable
Prevents inheritance
Prevents overriding
Prevents reassignment
Frequently asked in interviews ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐

Interview Questions

1. What is the purpose of the final keyword?

Answer: It prevents modification depending on where it is applied.

Why interviewers ask: To test your understanding of Java language features.

Common trap: Saying it always means "constant."


2. Can a final method be inherited?

Yes.

It is inherited but cannot be overridden.


3. Can a final class contain non-final methods?

Yes.

Although those methods are effectively final because inheritance is impossible.


4. Can a final class contain non-final variables?

Yes.

Variables must be explicitly declared final.


5. Why is the String class final?

To preserve immutability and prevent subclasses from altering its behavior.


6. Can constructors be final?

No.

Constructors are never inherited, so final has no meaning.


7. Can abstract and final be used together?

No.

A final method cannot be overridden, but an abstract method must be overridden.

Therefore, abstract final is illegal for both methods and classes.


Best Practices

  • Use final for constants.
  • Declare immutable classes as final.
  • Use final methods only when overriding must be prevented.
  • Don't mark every class as final.
  • Prefer readability and flexibility unless there's a strong design reason.

Quick Memory Trick 🧠

Remember CMV:

C → Class → No Child

M → Method → No Override

V → Variable → No Reassignment
Enter fullscreen mode Exit fullscreen mode

If you remember CMV, you'll always know what final does.


Key Takeaways

  • final is applicable to classes, methods, variables, and parameters.
  • A final class cannot be inherited.
  • A final method cannot be overridden.
  • A final variable can be assigned only once.
  • Methods inside a final class are effectively final.
  • Variables inside a final class are not automatically final.
  • String is a well-known example of a final class.
  • Use final only when you intentionally want to restrict modification.

What's Next?

In Part 3, we'll explore the abstract keyword, including:

  • Abstract classes
  • Abstract methods
  • Rules for abstract methods
  • Illegal modifier combinations
  • Real-world examples
  • Interview questions

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)