What are ways to Prevent Inheritance in Java Programming?

(Last Updated On: February 25, 2019)

There are 2 ways to stop or prevent inheritance in Java programming. By using final keyword with a class or by using a private constructor in a class.

How to prevent class from being inherited in java is one of the important technical interview questions for which we need to detail all possible solutions.

Problem Statement: Let’s say we have a class A and we don’t want to allow any other class to be derived from it. What are the possible solutions?


Solution-1: Using final keyword

Using final keyword before a class declaration we can stop a class to be inherited by other classes. For example,

If we try to extend the class A which is final, compiler will flash an error i.e.
“The Type B cannot the subclass the final Class A”, if class B is trying to extend final class A.

Solution-2: By making a class constructor private:

We can also stop a class to be extended/inherited by other classes in Java by making the class constructor private.

If we make the class constructor private we’ll not be able to create the object of this class from outside of this class. But, our purpose is to just prevent a class to be inherited and not to stop object creation. Hence, we need a method that can create an object of this class and return it.

We need to put a static method that will create and return an object. Why Static method? Because, from outside of a class, to call a normal method we need an object of the class, but, as constructor is private, we cannot create an object, hence, only solution is to have a static method that can be called using class name.

So, as a solution to stop a class to be extended, we need to make a constructor private and have one static method that will create an object of this class and return it.



NOTE: Interviewer looks for multiple solutions, but, here “final” keyword is just sufficient and better solution to prevent a class to be inherited in Java.