Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Final Class in Java – Tutorial with Examples

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

In Java, the ‘final’ keyword restricts the usage of classes, methods, and variables. When applied to a class, the ‘final’ keyword makes it impossible for the class to be subclassed. In simple words, no other class can inherit from a final class, ensuring that the class’s functionality remains unchanged and is not overridden. This article explains the final class in Java in depth.

Introduction to Final Class in Java

The concept of inheritance is fundamental to object-oriented programming in Java. It allows a class to inherit properties and behaviours (fields and methods) from another class. However, There are situations where you might want to prevent a class from being extended or modified. This is where the ‘final’ keyword comes into play. A class declared ‘final’ in Java cannot be subclassed, meaning no other class inherits from it.

How to Create Final Classes?

We can use Java’s final keyword to create a final class. This class definition should be complete and not abstract. Here is the syntax for creating the final class.

 

Syntax:

final class className { // Body of class }

In Java, we can define the final class using the final keyword by implementing the before-the-class keyword. The following source defines a class with two instance variables and one display method. Now, we create the object of the Vehicle class and call it the displayDetails method, which prints the model and brand.

 

The following program demonstrates the “how to use final class”:

 

Program

final class Vehicle { private String model; private String brand; public Vehicle(String model, String brand) { this.model = model; this.brand = brand; } public void displayDetails() { System.out.println("Model: " + model + ", Brand: " + brand); } } public class Main { public static void main(String[] args) { Vehicle myCar = new Vehicle("Model S", "Tesla"); myCar.displayDetails(); } }

Output

Model: Model S, Brand: Tesla

Java Final Variables

We can also use the final keyword to define the variables. Once initialised, a ‘final’ variable’s value cannot be changed. This property makes the ‘final’ variable useful for defining constants and ensuring their values remain constant throughout the program’s execution.

 

Let’s see “how we can declare the final keyword in Java before the variables’ type.

 

The following program demonstrates the final variables:

 

Program

public class Circle { private final double PI = 3.14159; private double radius; public Circle(double radius) { this.radius = radius; } public double calculateArea() { return PI * radius * radius; } public static void main(String[] args) { Circle circle = new Circle(5.0); double area = circle.calculateArea(); System.out.println("Area of the circle: " + area); } }

Output

Area of the circle: 78.53975
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Java Final Methods

In Java, the ‘final’ keyword can be applied to methods to indicate that subclasses cannot override them. When a method is declared ‘final’, no class that extends the current class can provide a different implementation. This is particularly useful to ensure that certain behaviour defined in a superclass remains consistent and cannot be altered by subclasses.

 

  • Inheritance: A ‘final’ method cannot be overridden by any subclass.
  • Usage: It ensures that the method’s implementation remains the same across all subclasses, guaranteeing its behaviour.
  • Design: It can prevent the modification of critical methods that are essential to a class’s integrity.

 

The following program demonstrates the final method in Java:

 

Program

class Animal { public final void makeSound() { System.out.println("Some generic animal sound."); } } class Dog extends Animal { // Body of the Dog class } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); myDog.makeSound(); // Output: Some generic animal sound. } }

Output

Some generic animal sounds.

Advantages of Final Class

In Java, the ‘final’ keyword can be used with classes to prevent them from being subclassed. Here are some key advantages of using a ‘final’ class.

 

  • Security: Marking a class as ‘final’ ensures that other classes cannot extend or modify it. It is particularly useful for securing critical parts of an application or library where you want to prevent unauthorised or potentially harmful modifications.
  • Integrity: By making a class ‘final’, We can ensure that the implementation remains consistent and unaltered. This can be important for classes that provide fundamental or standardised functionality, where modification could lead to unexpected behaviour or bugs.
  • Simplicity: The class is ‘final’. It simplifies the class hierarchy by preventing further subclassing. This can make the source code easier to understand and maintain, as developers can be sure that the class’ behaviour is not altered through inheritance.
  • Thread Safety: Immutable classes are inherently thread-safe. By making a class ‘final’, We can help ensure that its instances are immutable and thus safe to use in concurrent programming scenarios.

 

Also Check: Java Tutorial for Beginners

Disadvantages of Final Class

The final class has some advantages and disadvantages. Here’s a list of the disadvantages of the final class.

 

  • Inflexibility in Extensibility: This prevents other classes from extending or inheriting the final class, limiting the ability to add or modify functionality.
  • Difficulty in Testing and Mocking: It makes it challenging to mock or stub final classes in unit tests, especially with frameworks that rely on inheritance.
  • Limitation in Design Patterns: It cannot be used in design patterns that require inheritance, such as the template method pattern, reducing design options.
  • Minimal Performance Gains: While final classes can offer slight performance optimisations, the benefits are often minimal compared to the loss of flexibility.

Conclusion

In Java, a final class is a powerful feature that helps maintain the integrity of your software code. By declaring a class as ‘final’, you ensure that no other class can extend it, which can be crucial for classes that handle sensitive operations or are integral to a critical library.

This restriction helps secure the class’s functionality and allows the JVM (Java Virtual Machine) to optimise performance, as it knows the class’s implementation will not be altered through inheritance. Furthermore, using ‘final’ classes simplifies design and implementation by minimising inheritance-related issues, thereby reducing the need for extensive testing and debugging.

FAQs
A final class in Java is a class that cannot be subclassed or extended. No other class can inherit from it once a class is declared ‘final’, ensuring its behaviour remains unchanged.
No, A final class cannot have subclasses. Once a class is declared as ‘final’, it cannot be extended by any other class.
Yes, A final class can implement one or more interfaces. The ‘final’ keyword only prevents the class from being subclassed, not from implementing interfaces.
We cannot override methods in a final class because you cannot subclass the final class itself. Methods within a final class are inherently final in practice as they cannot be overridden by any subclass.
The final classes prevent inheritance, which can help maintain the security, integrity, and performance of the source code.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved