简体   繁体   中英

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?

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 .

Private constructors are used to stop other classes from creating an object of the "Class" which contains the private constructor.

This is done to provide the singleton pattern where only a single instance of the class is used.

The code that you have mentioned is supposed to create just one instance of the class and use that instance only to perform all the operations of that class. But you have modified the code which violates the singleton design pattern.

Why do we need a private constructor at all?

Basically 3 reasons:

  1. if you don't want the user of the class creates an object directly, and instead use builders or similars,

  2. if you have a class defined for constants only, then you need to seal the class so the JVM don't create instances of the class for you at runtime.

  3. singletons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM