Final Class in Java
The final class is a class that is declared with the final keyword. Subclasses can't inherit a final class, and any subclass cannot inherit a final class. So, we can restrict class inheritance by using a final class.
Introduction to Final Class in Java
As the name suggests, the Final Class in Java uses the final keyword for its declaration. The final keyword in Java restricts the user; similarly, the final class means that the class cannot be extended. We can only create a final class if it is complete, which means it cannot be an abstract class. All wrapper classes in Java are final classes, such as String, Integer, etc. Any subclass cannot inherit final class,
If we try to inherit a final class, the compiler throws an error during compilation.
How to Create Final Classes?
We can use Java's final keyword to create a final class. The class's definition should be complete and not abstract.
Syntax:
where final is the keyword used to declare the final class and className is the name of the class we are defining.
Example 1: How to Use Final Class?
We can simply define a final class using the final keyword and can write the class body code according to our needs.
In the code below, we are creating a final class named myFinalClass, which has a method called myFinalMethod() that prints some text. So for using our final class, we are just creating an instance of our final class in our main class; now, we are just calling our method myFinalMethod() from the class instance, which prints the final output of our code.
Output:
Simply the print statement present inside myFinalMethod is executed.
Example: 2 What happens if we try to inherit from a final Class?
In the below code, we are using the extend keyword to inherit the final class to the subClass but any other subclass cannot inherit the final class so it will throw an error saying "cannot inherit from final myFinalClass"
Output:
We got an error when we tried to inherit from our final class
Advantage of the Final Class
- The Final class provides security as it cannot be extended or inherited by any other class. Classes that can be extended can leak potential users' sensitive data, but final classes make data elements safe and secure.
- The final class is complete and immutable, so external access does not change data elements.
Conclusion
- The final class is a class that is declared with the final keyword.
- We can restrict class inheritance by making use of the final class.
- Final classes cannot be extended or inherited.
- If we try to inherit a final class, the compiler throws an error during compilation.
- We can simply define a final class using the final keyword and write the class body code according to our needs.
- As the final class is immutable and can't be inherited, it has some advantages, such as immutability and security.