Why can you not inherit from a class whose constructor is private?

Why does Java disallow inheritance from a class whose constructor is private?


Solution 1:

Java doesn't prevent sub-classing of class with private constructors.

public class Main {
    static class A {
        private A() {
            System.out.println("Subclassed A in "+getClass().getName());
        }
    }

    static class B extends A {
        public B() {

        }
    }

    public static void main(String... ignored) {
        new B();
    }
}

prints

Subclassed A in Main$B

What it prevents is sub-classes which cannot access any constructors of its super class. This means a private constructor cannot be used in another class file, and a package local constructor cannot be used in another package.

In this situation, the only option you have is delegation. You need to call a factory method to create an instance of the "super" class and wrap it.

Solution 2:

Because a class must call its super class constructor always. If the super class constructor can't be accessed, then the sub class can't be initialized.

More info: JLS 8.8.10. Preventing Instantiation of a Class


Regarding Brian Roach's comments:

The call [to the parent class constructor] is only implicit if you don't do it explicitly and the parent has a public or protected no-arg constructor (or hasn't defined any in which case there's a default no-arg). It's required because ... that's how the language works. Children [classes] must call [their] parent's constructor.

Note that when you instantiate any class in Java, there's always a implicit call to Object constructor since it is the super class of all classes. It will execute its default constructor:

public Object() {
}

Note from the JLS link:

It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.

Solution 3:

If constructor of a class is private then child class cannot make call to super constructor. Hence inheritance would fail.

Solution 4:

If you have a subclass, you have 2 possiblities for child class(subclass) constructors : 1. Default Constructor(No argument constructor) : In this case default constructor will automatically try to call the parent class constructor : this will fail since parent class constructor is private. 2. Parameterized Constructor : When you try to create an object for a child class which has parameterized constructor, you need to mandatorily call parent class constructor from child class constructor by either passing parameters or not passing parameters : this will also fail since parent constructor is private.

Since child class will have either default constructor or parameterized constructor and its not possible to have either of them, you cannot have a subclass for a parent class with private constructor.