C

Core Java tutorial for beginners

Clean • Professional

Java - final Keyword in Classes, Methods, and Variables

5 minute

final Keyword in Java (Classes, Methods, and Variables)

In Java, the final keyword is a non-access modifier that can be applied to variables, methods, and classes.

It is used to restrict modification — once something is declared final, it cannot be changed, overridden, or extended, depending on where it is used.


final Variables (Constants)

A final variable means its value cannot be changed after initialization.

It becomes a constant, similar to constants in other programming languages.

Syntax

final dataType variableName = value;

Example – Final Variable

class FinalVariableExample {
    final int SPEED_LIMIT = 80;

    void display() {
        // SPEED_LIMIT = 100;  Error: cannot assign a value to final variable
        System.out.println("Speed limit: " + SPEED_LIMIT);
    }

    public static void main(String[] args) {
        new FinalVariableExample().display();
    }
}

Output:

Speed limit: 80

Ways to Initialize a Final Variable

learn code with durgesh images

TypeExample
1. At declarationfinal int a = 100;
2. In constructorAssign in constructor — useful for instance-specific constants
3. In static blockFor static final variables

Types of Final Variables

learn code with durgesh images

TypeDescriptionExample
Instance variableBelongs to an objectfinal int x = 10;
Static variableShared constant for all objectsstatic final double PI = 3.14159;
Blank final variableDeclared but not initialized immediatelyMust be initialized in the constructor
Final parameterMethod parameter whose value cannot be changed inside the methodvoid show(final int num)

Example – Blank Final Variable

class Student {
    final int rollNo; // blank final variable

    Student(int rollNo) {
        this.rollNo = rollNo; // must be initialized in constructor
    }

    void display() {
        System.out.println("Roll No: " + rollNo);
    }

    public static void main(String[] args) {
        Student s = new Student(101);
        s.display();
    }
}

Output:

Roll No: 101

final Methods

A final method cannot be overridden in a subclass.

This ensures that the method’s behavior remains unchanged for all subclasses.

Syntax

class Parent {
    final void show() {
        System.out.println("This is a final method.");
    }
}

Example – Final Method

class Parent {
    final void display() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    // void display() { }  Error: Cannot override final method
}

public class FinalMethodExample {
    public static void main(String[] args) {
        Child c = new Child();
        c.display();
    }
}

Output:

Parent method

Use Case:

Mark methods as final when you want to prevent subclasses from changing important behavior — like security, logging, or framework methods.


final Classes

A final class cannot be extended (inherited) by any other class.

This ensures that the class’s structure and behavior cannot be modified through inheritance.

Syntax

final class ClassName {
    // class body
}

Example – Final Class

final class Vehicle {
    void run() {
        System.out.println("Vehicle is running...");
    }
}

// class Car extends Vehicle { }  Error: cannot inherit from final Vehicle

public class FinalClassExample {
    public static void main(String[] args) {
        Vehicle v = new Vehicle();
        v.run();
    }
}

Output:

Vehicle is running...

Use Case:

  • Use final classes for security, immutability, or performance reasons.
  • Example: The String class in Java is final, so it cannot be extended.

Combining final with static

When you combine static and final, the variable becomes a constant (a fixed value for the whole class).

Example – Static Final Constant

class Constants {
    static final double PI = 3.14159;
    static final int MAX_USERS = 100;
}

public class StaticFinalExample {
    public static void main(String[] args) {
        System.out.println("PI = " + Constants.PI);
        System.out.println("Max Users = " + Constants.MAX_USERS);
    }
}

Output:

PI = 3.14159
Max Users = 100

Commonly used for mathematical constants, configuration values, or fixed limits.


Key Differences

Use of finalRestriction
VariableValue cannot be changed
MethodCannot be overridden
ClassCannot be inherited

Real-World Examples

Use CaseExample
Constant valuespublic static final int MAX_RETRY = 3;
Prevent inheritancefinal class String { ... }
Prevent overridingfinal void processPayment()
Security and consistencyPrevents changes in critical methods or API classes

Common Mistakes / Notes

  • You must initialize a final variable (either immediately or in a constructor).
  • finalfinally (exception handling) ≠ finalize() (object cleanup).
  • final objects → their reference cannot change, but their internal data can (if mutable).

Example – Final Object Reference

class Demo {
    int data = 10;
}

public class FinalObjectExample {
    public static void main(String[] args) {
        final Demo obj = new Demo();
        obj.data = 20; //  allowed (object data can change)
        // obj = new Demo();  not allowed (reference can't change)
        System.out.println(obj.data);
    }
}

Output:

20

Points to Remember

  • final is a restriction keyword: no change allowed.
  • Use final to create constants, secure methods, and non-extendable classes.
  • Common combinations: static final for constants.
  • Widely used in frameworks, APIs, and libraries to maintain integrity.
Article 0 of 0