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
or default
(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. So private
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. Using private
constructor we can ensure that no more than one object can be created at a time.
Example -
public class Database {
private static Database singleObject;
private int record;
private String name;
private Database(String n) {
name = n;
record = 0;
}
public static synchronized Database getInstance(String n) {
if (singleObject == null) {
singleObject = new Database(n);
}
return singleObject;
}
public void doSomething() {
System.out.println("Hello StackOverflow.");
}
public String getName() {
return name;
}
}
More information about access modifiers.