Java 'final' Keyword Tutorial

The final keyword in Java is used to restrict the user. The java final keyword can be used in many contexts. Final can be: variable, method, and class.

1. Java Final Variable

If you make any variable as final, you cannot change the value of final variable (It will be constant).

class Bike9 {
 final int speedlimit = 90; //final variable
 void run() {
  speedlimit = 400;  //Compile Time Error
 }
}

2. Java Final Method

If you make any method as final, you cannot override it.

class Bike {
  final void run() { System.out.println("running"); }
}
class Honda extends Bike {
   void run() { System.out.println("running safely with 100kmph"); } //Compile Time Error
}

3. Java Final Class

If you make any class as final, you cannot extend it.

final class Bike {}

class Honda1 extends Bike { //Compile Time Error
  void run() { System.out.println("running safely with 100kmph"); }
}

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.