Search code examples
javainheritanceconstructordefault-constructor

Why does private constructor prohibits a inheritance?


I know two ways, which prohibit inheritance:

  • make a final class
  • announce a private constructor

To prevent the inheritance must the default constructor of the class announces as private.

class Class {
    private Class() {}    
}

class OtherClass extends Class {
    // Error! There is no default constructor available
}

Did everything done for using super?

class Class {
    public Class() {}
}

class OtherClass extends Class {
    public OtherClass() { super(); } // Did everything done for this opportunity?
}

I want to know why you can not inherit from a class with private default constructor and what is conditioned by?


Solution

  • In Java, if you create an instance of Child Class, Parent Class instance gets created implicitly. So Parent Class constructor should be visible to Child Class as it calls the constructor of Parent Class constructor using super() in the first statement itself.

    So if you change the constructor of the Parent Class to private, Child Class could not access it and could not create any instance of its own, so compiler on the first hand just does not allow this at all.

    But if you want to private default constructor in Parent Class, then you need to explicitly create an overloaded public constructor in the Parent Class & then in Child class constructor you need to call using super(param) the public overloaded constructor of Parent Class .

    Moreover, you might think then what's the use of private constructors. private constructors is mostly used when you don't want others from any external class to call new() on your class. So in that case, we provide some getter() method to provide out class's object.In that method you can create/use existing Object of your class & return it from that method.

    Eg. Calendar cal = Calendar.getInstance();. This actually forms the basis of Singleton design pattern.