CodeBlue CodeBlue - 4 months ago 10
Java Question

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

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

Answer

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.