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.
final class Car {
Car() {
System.out.println("final class: Car");
}
public void run() {
System.out.println("Car running...");
}
}
If you try to extend the final class Car as below, you will get compiler error.
//Cannot extend final class Car
class Maruti extends Car{
}
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.
/*----------------------------------------
* Final class in java program example.
* */
/*----------------------------------------
* Car class cannot be extended/inherited by
* subclasses /derived classes
*
* */
final class Car {
Car() {
System.out.println("final class: Car");
}
public void run() {
System.out.println("Car running...");
}
}
/*----------------------------------------
* Final class java - test program
* create object of the final class
* call methods from the final class etc.
* */
public class FinalClassJava {
public static void main(String[] args) {
Car c = new Car();
c.run();
}
}
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.