Keyword final in Java

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

  • Class
  • Method
  • Variable

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 cannot 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 or 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.

Example

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();
   car.setMaxSpeed(320);
  }
}


That’s it!

Leave a Reply

Your email address will not be published.