Final Class in Java – Definition, Syntax, and Example

Java Final Class: Key Points, Examples, FAQs & Related Links | YourBlogName

Java Final Class: Complete Guide with Examples

In Java, the final keyword can be applied to classes, methods, and variables. When a class is declared final, it cannot be extended (inherited) by any other class. This ensures the class implementation remains unchanged and secure.

Key Points of Final Class

  • Cannot be inherited – No other class can extend a final class.
  • Prevents modification – Its implementation remains unchanged.
  • All methods are final – Methods cannot be overridden in child classes.
  • Used for immutability – Often used to create immutable classes (e.g., String).
  • Improves security – Prevents alteration of critical code.
  • Declared using the final keyword.

Syntax

final class ClassName {
    // fields and methods
}

Example

// Final class
final class Vehicle {
    void display() {
        System.out.println("This is a vehicle");
    }
}

// Trying to inherit (will cause error)
class Car extends Vehicle {  // ❌ Error
    void show() {
        System.out.println("This is a car");
    }
}

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

Output:

This is a vehicle

If inheritance is attempted, the compiler shows error:
error: cannot inherit from final Vehicle

Frequently Asked Questions (FAQ)

Q1: What happens if I try to extend a final class?

A: The compiler will generate an error because final classes cannot be subclassed.

Q2: Can final methods be overridden?

A: No, methods declared as final cannot be overridden in any subclass.

Q3: Why use final classes?

A: To create immutable classes, increase security, and prevent modification through inheritance.

Q4: Are all methods in a final class automatically final?

A: No. Declaring a class as final only prevents inheritance, but methods inside it are not implicitly final unless declared so.

Comments

Popular posts from this blog

Introduction to Java

Java Classes in Depth – Complete Guide with Definitions, Syntax & Examples

Top AI Tools for Social Media Marketing in 2025 – Automate & Grow Your Brand