# "final" keyword in Java

In 
Published 2022-12-23

This tutorial explains to you how final keyword in Java.

# "final" keyword in Java - theory

The final keyword in java is used in declaring:

  • a class : that class cannot be extended (no inheritance)
  • a variable : that variable is a constant
  • a method : that method can't be overridden (but can be overloaded)

# "final" keyword in Java - example

Here are some examples using the final keyword in Java:

Car.java
public class Car {

    float speed;
     
    //final variable 
    final int speedLimit=120;
     
    //blank final variable: this can be initialized only in constructor
    final String colour;
     
    //static blank final variable: this can be initialized only in static block
    static final int warrantyPeriod;
    static {
        warrantyPeriod = 4;
    }
     
    public Car() {
        colour = "green";
        speed = 0;
    }   
     
    public Car(final String colour) {
        this.colour = colour;
        speed = 0;
    }   
     
    public final void startCar() {
        System.out.println("START the "+colour+" Car.");
    }
     
    public void stopCar() {
        System.out.println("STOP the "+colour+" Car.");
    }
 
    public float getSpeed() {
        System.out.println("The speed of the Car is "+ speed +" km/h");
        return speed;
    }
 
    public void setSpeed(float speed) {
        System.out.println("The speed of the Car is set at "+speed+" km/h");
        this.speed = speed;
    }
}
MainApp.java
public class MainApp {

    public static void main(String [] args) {
        Car car = new Car();
        car.setSpeed(12);
        car.startCar();
        System.out.println("The speed limit of the car is "+car.speedLimit+" km/h.");
        System.out.println("The colour of the car is "+car.colour+".");
 
    }
}

When you run this code you will see that the result is :

The speed of the Car is set at 12.0 km/h
START the green Car.
The speed limit of the car is 120 km/h.
The colour of the car is green.

Process finished with exit code 0