← Back to Chapters

Java final Keyword

? Java final Keyword

? Quick Overview

The final keyword in Java is used to restrict modification. It can be applied to variables, methods, and classes to enforce immutability and prevent inheritance or overriding.

? Key Concepts

  • final variable Value cannot be changed
  • final method Cannot be overridden
  • final class Cannot be inherited

? Syntax / Theory

  • Final variables behave like constants
  • Final methods lock behavior in inheritance
  • Final classes improve security and design stability

? Code Examples

? View Code Example
// Example of final variable
class Demo {
final int MAX = 100;

void show() {
System.out.println(MAX);
}
}
? View Code Example
// Example of final method
class Parent {
final void display() {
System.out.println("This method cannot be overridden");
}
}
? View Code Example
// Example of final class
final class SecureClass {
void info() {
System.out.println("This class cannot be inherited");
}
}

⚡ Interactive Simulator

Type a value below and click "Initialize". Once it's final, you cannot change it!

final String myData = "";
> Waiting for initialization...

? Live Output / Explanation

Output Explanation

The compiler ensures that:

  • Final variables are assigned only once
  • Final methods remain unchanged in subclasses
  • Final classes cannot be extended

✅ Tips & Best Practices

  • Use final for constants to improve readability
  • Prefer final classes for utility and security-sensitive code
  • Final methods help maintain consistent behavior

? Try It Yourself

  • Create a final variable and try modifying it
  • Attempt to override a final method
  • Try extending a final class