piepi piepi - 1 month ago 6
Java Question

Why do we need a private constructor at all?

This answer says that we can't instantiate more than one object at a time via

private
constructors. I have modified the code which does just the opposite:

class RunDatabase{
public static void main(String[] args){
Database db = Database.getInstance("hello");//Only one object can be instantiated at a time
System.out.println(db.getName());
Database db1 = Database.getInstance("helloDKVBAKHVBIVHAEFIHB");
System.out.println(db1.getName());
}
}
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) {
Database singleObject = new Database(n);
}

return singleObject;*/

return new Database(n);
}

public void doSomething() {
System.out.println("Hello StackOverflow.");
}

public String getName() {
return name;
}
}


And as expected both the strings are being printed. Did I miss something?

Answer

We can't instantiate more than one object at a time via private constructors.

No, we can. A private constructor only avoids instance creation outside the class. Therefore, you are responsible for deciding in which cases a new object should be created.

And as expected both the strings are being printed. Did I miss something?

You are creating a new instance every time the getInstance method is called. But your commented code contains a standard lazy initialization implementation of the singleton pattern. Uncomment these parts to see the difference.

Other singleton implementations you can look over here.

Comments