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?
Answer:
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,
public final class A
{
}
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.
public class B extends A{//Error :The Type B cannot the subclass the 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.
class A {
// Make constructor private to prevent object creation
//From outside of this class.
private A() {
}
//Static method to create and return an object.
//this method will be called from outside by using
//class name only.
public static A GetInstance() {
return new A();
}
}
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.