Keyword final in Java

The Java keyword final can be used in the declaration of a:

Java final Class

If we want to prevent the inheritance of a class, then we will declare it with the keyword final.

If we try to extend a final class, we will get a compiler error:

final class Vehicle {
class Car extends Vehicle { // DOES NOT COMPILE

Java final Method

If we declare any method as final, we can inherit it but not override it.

class Vehicle {
  public final void methodA() {
    // ...
class Car extends Vehicle {
  public void methodA() { // DOES NOT COMPILE
    // ...

Java final Variable

Declaring a variable using the final modifier ensures that its value ​​cannot be changed after the first assignment. It will act as a constant.

Some rules to follow when working with the final fields:

  • Static final field – we can assign the value immediately during declaration or in a static class initializer.
  • Non-static final field – we can assign the value immediately during declaration, in the object initializer, or in all constructors.
  • Local variables – we can assign the value later, but after that, it is no longer possible to change it.


class Car {
  private final int maxSpeed = 300;
  public void setMaxSpeed(int newMaxSpeed) {
    maxSpeed = newMaxSpeed; // DOES NOT COMPILE
  public static void main(String[] args) {
   Car car = new Car();

I hope this tutorial was helpful to you. To learn more, check out Java Tutorials page. 

Happy learning!

Leave a Reply

Your email address will not be published.