Final class in Java

(Last Updated On: March 7, 2019)

Learn Final class in java with program example, uses and if using final class is important in java applications.

In java programs, a class is made a final class to stop its extension. Means, if a class is final, it cannot be inherited or extended by sub classes /derived classes.

Prerequisite: Concept of inheritance in java.

To make a class final, yo just need to use final keyword before class declaration as below.

If you try to extend the final class Car as below, you will get compiler error.

 

Note that by making final class, you are just stopping the class to be inherited. Otherwise, final class is as normal class in java. Means, we can create objects of the class and call methods in java program etc.

Example : Can create object of final class and call methods.

Output:
final class: Car
Car running…

NOTE:

If we don’t make a final class in the software project, it will still work, but, this is the best practice to make a class final if it is not required to be inherited or due to some constraint it is not required to be inherited. So, it cannot be inherited accidentally.

If a software developer will try to inherit it unknowingly somewhere in the software product or software project, then compiler will complain and flash an error at compile time itself. Due to the compiler complain, the programmer will analysis the intention of making the class final and proceed accordingly.