Do constructors always have to be public? [duplicate]

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.


Solution 1:

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.

Solution 2:

Yes , Constructors can have any access specifier/access modifier.

Private constructors are useful for creating singleton classes.

Singleton - A singleton class is a class where only a single object can be created at runtime (per JVM) .

A simple example of a singleton class is -

class Ex {
    private static Ex instance;
    int a;
    private Ex() {
        a = 10;
    }
    public static Ex getInstance() {
        if(instance == null) {
            instance = new Ex();
        }
        return instance;
    }
}

Note, for the above class, the only way to get an object (outside this class) is to call the getInstance() function, which would only create a single instance and keep returning that.

Also, note that this is not thread-safe.

Solution 3:

Constructors could be public, default or private and it all depends on what you want to do with it.

For example, if you are defining a Singleton class, you'd better hide (meaning making it private so that it is only available to the class where it belongs) the constructor to prevent other classes to instantiate your class at their will.

You may want to declare it default, let's say, for testing purposes so that test cases within the same package could access it.

More detailed info could be found here