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,protectedordefault(no access modifier at all).Making something
privatedoesn't mean nobody can access it. It just means that nobody outside the class can access it. Soprivateconstructor is useful too.One of the use of
privateconstructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Usingprivateconstructor we can ensure that no more than one object can be created at a time.Example -
More information about access modifiers.