My first question is -
class Explain() {
public Explain() {
}
}
Should Constructor always declared as public?
What if I create a private
constructor.
I always seen constructors are implicitly public
. So why private
constructor is useful? Or is it not useful at all. Because nobody could ever call it, or never make an object(because of the private
constructor) ! And that is my second question.
No, Constructors can be
public
,private
,protected
ordefault
(no access modifier at all).Making something
private
doesn't mean nobody can access it. It just means that nobody outside the class can access it. Soprivate
constructor is useful too.One of the use of
private
constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Usingprivate
constructor we can ensure that no more than one object can be created at a time.Example -
More information about access modifiers.