Search code examples
javaconstructorsingletonprivate-constructor

Preventing call of a private constructor from within the class in Java


We can restrict the creation of object of a class by making its constructor private. But this constructor could still be called from within the class. Is there any way to prevent this in Java?

Thanks.


Solution

  • No, there is no clean way to do this. And really I cannot see a reason to do so. Because if the constructor is private, this means that he can only be called from code within this exact class (no subclasses, or other classes in the package), so if you do not want the constructor to be called, put a comment on it which says so.

    Since everyone who is able to use the constructor would be able to remove any measures you put there to prevent the calling of the constructor, it would have no real effect.

    Besides, if you need a singleton, then you may want the constructor to be run at least once (except if your idea of a singleton is a purely static class).