Introduction

Object-Oriented Programming (OOP) is a powerful paradigm that enables developers to model real-world entities as objects.

In the world of OOP, understanding key concepts of 'final' keyword is crucial. This blog post will delve deeply into the topic, providing comprehensive explanations and real-world examples to ensure a thorough understanding.

Stay connected till the end to get complete knowledge about it...

In Java and many other object-oriented languages, the 'final' keyword is used to define a constant value that cannot be changed once assigned.

Let's first talk about the Final Variable

In this example, the 'PI' variable is declared as "final", so no changes to the value can be made

Let's cross-check it by updating its value,

And as declared you cannot change the value of the "final" value,  ensuring its value remains constant throughout the program.

I hope the final keyword with a variable is clear to you, now time to see the final keyword with a method.

Additionally, 'final' can also be used to make a class, or method immutable, preventing further modifications.

Time to talk about Final Method

When a method is declared as final in a class, it means that the method cannot be overridden by any subclass. This ensures that the behavior of the method remains constant and cannot be changed by any inheriting class.

Let's take an example with "Shape" as a parent class and "Circle" as a child class inheriting the properties and behaviour of it's parent class i.e. Shape class

Now because the Shape class has a non-final method as "draw()", the child class i.e. Circle class can easily override it with no errors.

But what if draw() will be the final method?

So, what we have seen if the method is declared as a final method you can not override it. The final method becomes freeze.

From here we have a clear cut about final methods that are commonly used in situations where the logic of a method should not be altered in any derived class.

Now time to see the concept of the final keyword with the class.

Final Class

When a class is declared as final, it means that the class cannot be subclassed. In other words, no other class can extend a final class.

Try to understand with an example: In the previous example we have seen that Shape was a non-final class and the child class, Circle can easily inherit it.

But what if we will make the Shape class to be a final class?

In this example, the Shape class is declared as final, so any attempt to create a subclass, like Circle, will result in a compilation error.

So, we have seen that no other class can extend a final class.

The concept of the "Final" keyword with classes is useful when you want to prevent further modification or extension of a specific class, ensuring its integrity and functionality.

I hope in this blog, you get a clear idea about the "final" keyword.