Why do we use final class in java? – Is it necessary?

Final class in java programs is used to stop inheritance / extension. If we don’t want a class to be inherited or not to be sub classed then make it as a final in software products/projects.

Except extension,  in java final class is used as normal class. Means, we can create objects of the class, call methods from the class etc.
To make a class final, just we need to write the “final” keyword before the class. That’s simple and nothing has to do. If we try to inherit or extend final class then compiler will flash an error. Below is an example for final class.

Final class example program

/*----------------------------------------
 * Final class example in java.
 * */

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
 * call methods etc.
 * */
public class FinalClassJava {

	public static void main(String[] args) {
		
		Car c = new Car();
		c.run();

	}

}

Output:
final class: Car
Car running…

If we don’t use final class in java programs, it will still work, but, this is the best practice to make a class final if we think, that the class should not be inherited throughout the program. Or, may be due to some reason we may want to restrict the extension of the class. So, a software programmer cannot extend it accidentally.

If a programmer will try to inherit it unknowingly, compiler will flash an error and warn programmer to analyse the intention behind making the class final and act accordingly. He can ask his manager or leader if he really wants to extend it. If he is allowed final class can be make as a normal class by removing the final keyword before class or else he should write his own definitions in his class rather that re-using the existing final class.

Tips: In interview, most candidate gives one liner answer that a final class is used to stop extension. That’s it. This would not be the satisfactory answer. So, we need to answer in detail with example and reason.

Related Posts