⬅ Previous Topic
Java final MethodsNext Topic ⮕
Inheritance in Java⬅ Previous Topic
Java final MethodsNext Topic ⮕
Inheritance in JavaIn Java, the final
keyword when used with a class, it signals that the class cannot be subclassed or extended.
This concept is especially valuable when you want to design components that are not meant to be changed through inheritance — for example, utility or security-related classes.
Marking a class as final
is a purposeful decision. Here’s why developers often do it:
final class Vehicle {
void displayType() {
System.out.println("This is a vehicle.");
}
}
Here, the Vehicle
class is declared final
, which means:
final class Vehicle {
void displayType() {
System.out.println("This is a vehicle.");
}
}
class Car extends Vehicle { // ❌ Compilation Error
void showModel() {
System.out.println("This is a sedan.");
}
}
Error: Cannot inherit from final 'Vehicle'
You can still create objects and call its methods as usual:
final class Logger {
void log(String message) {
System.out.println("LOG: " + message);
}
}
public class Main {
public static void main(String[] args) {
Logger logger = new Logger();
logger.log("Application started");
}
}
LOG: Application started
Java itself defines several final classes:
java.lang.String
— Immutable text.java.lang.Math
— Utility class for mathematical operations.java.lang.System
— System-level utilities.These classes are final because altering their behavior could break Java’s core functionality or create serious security vulnerabilities.
Use final
when:
Yes! In fact, you can declare methods as final to prevent them from being overridden in subclasses (though in a final class, overriding is impossible anyway).
final class Shape {
final void draw() {
System.out.println("Drawing shape...");
}
}
This is often done to document intention — even if inheritance is blocked, the developer is being explicit that the method shouldn't be touched.
The final keyword, when applied to classes, enforces boundaries, supports clean API design, and aligns with object-oriented principles like encapsulation and immutability.
While it may seem restrictive at first glance, it encourages you to write intentional, safe, and maintainable code.
final
in Java achieve?final class Vehicle {
void showType() {
System.out.println("Vehicle");
}
}
class Car extends Vehicle {
void showModel() {
System.out.println("Sedan");
}
}
⬅ Previous Topic
Java final MethodsNext Topic ⮕
Inheritance in JavaYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.