Final Class in Java – Definition, Syntax, and Example
![]() |
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)
A: The compiler will generate an error because final classes cannot be subclassed.
A: No, methods declared as final cannot be overridden in any subclass.
A: To create immutable classes, increase security, and prevent modification through inheritance.
A: No. Declaring a class as final only prevents inheritance, but methods inside it are not implicitly final unless declared so.
Comments
Post a Comment