Skip to main content

Posts

Showing posts from May, 2020

Class with a private constructor

In "Cracking the Coding Interview" by J. Laakmann McDowell, I found an interesting question concerning the influence of private constructors on inheritance in Java. I know that this is not forbidden in Java, so I'm wondering in which cases it might be useful. In Java, it is not possible to inherit a class with a private constructor. But if this class is internal, the parent class can access all private methods of internal classes. Thus, the inheritance of internal classes with private constructors is possible in the scope of the parent class. I think this is useful for implementing Singletons. I want to demonstrate these cases in the following example: import java.util.*; import test.*; public class Main { class PrivateClassA { private PrivateClassA () { System.out.println( "Private constructorA" ); } } /* PrivateClassB inherits the class with the private constructor */ class PrivateC...