Do constructors always have to be public?

62.5k views Asked by At

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.

11

There are 11 answers

11
Dhanuka On BEST ANSWER

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.

0
Nitesh Soomani On

No,Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)

Example

class Alpha {
   static String s = " ";
   protected Alpha() { s += "alpha "; }
 }
 class SubAlpha extends Alpha {
   private SubAlpha() { s += "sub "; }
 }
 public class SubSubAlpha extends Alpha {
   private SubSubAlpha() { s += "subsub "; }
   public static void main(String[] args) {
     new SubSubAlpha();
     System.out.println(s);
   }
 }

Output of above program will be

alpha subsub

4
Marc Giombetti On

I agree with the previous answers that a Singleton is a good example of a class having a private constructor. I would though recommend a different implementation: a thread safe Singleton:

/**
 * Thread safe singleton
 */
public class Singleton {

    private static volatile Singleton instance = null;

    /**
     * Private constructor
     */
    private Singleton() {
    }

    /**
     * Gets the Instance of the Singleton in a thread safe way.
     * @return
     */
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Using a singleton in a thread safe way will safe you a lot of pain in parallel code.

0
Teepeemm On

Most of these answers refer to a singleton or factory class. Another time a private constructor appears is (for example) in the java.lang.Math class, where everything is static and no one should ever call the constructor (including the class itself). By having the private constructor, you prevent anyone outside the class from calling the constructor. (This doesn’t prevent someone inside the class from calling the constructor, but then they’re breaking their own rule.)

0
supercat On

Others have noted that constructors may have access modifiers; an aspect not yet mentioned is that the aspect modifiers on a constructor control two very different aspects of construction, but do not allow them to be controlled separately:

  1. Who is allowed to create instances of ClassName and what constructors are they allowed to use.
  2. Who is allowed to create extensions of ClassName and what constructors are they allowed to use.

Both Java and .NET require that the answers to those two questions go together; if a class isn't final (or sealed) and allows a constructor to be used by outside code to create new instances, then outside code will also have total freedom to use that same constructor to create derived types.

In many cases, it may be appropriate for a class to have only package-private (internal) constructors, but expose public methods that return new instances. Such an approach might be used if one were designing a type like String from scratch; a package including String could define it as an abstract type but include concrete derived types like AsciiString and UCS16String which store their content as a byte[] and Char[], respectively; methods that return String could then return one of the derivatives depending upon whether the string contained characters outside the ASCII range. If neither String nor any derived types expose any constructors outside its package, and all derived types within the package behave as a string would be expected to behave, then code which receives a reference of type String could expect it to behave sanely as a string (e.g. guaranteeing that any observations about its value will forevermore remain true). Exposing constructors outside the package, however, would make it possible for derived types to behave in weird and bizarre fashion (e.g. changing their contents after they've been examined and validated).

From a syntactical perspective, being able to say Fnord foo = new Fnord(123); is a little nicer than having to say Fnord foo = Fnord.Create(123);, but a class Fnord that requires the latter syntax can maintain much better control over the object-creation process.

3
Anand S Kumar On

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.

0
Nimishan On

The simple explanation is if there is no constructor in a class, the compiler automatically creates a default constructor.

The constructor is not always declared as public, it can also be private, protected, or default.

The private constructors prevent a class from fully and clearly expressed/represented by its callers. In that case private constructors are useful. And if if we do not need our class to be sub-classed, we can use private constructors.

0
Alp On

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

0
A.v On

Constructors can have all kind of access modifiers. The usage of different access modifier on constructors are different.

You make a constructor public if you want the class to be instantiated from any where.

You make a constructor protected if you want the class to be inherited and its inherited classes be instantiated.

You make a constructor private if you want the class to be instantiated just from its own members usually a static block or static method. It means that you take control of instantiating the class and apply some rule on instantiation. Example of usage of private constructor is singleton design pattern.

5
Arthur Eirich On

A constructor has to be at least protected or even private while creating, for example, custom factory classes, like:

public final class MyFactory {
  private MyFactory(){} // this one prevents instances of your factory
}

public static void doSomething(){} // access that with MyFactory.doSomething

Note that this is only one example showing when a constructor shouldn't be public.

2
Aston Ray On

There is no rule that constructor to be public .Generally we define it public just because we would like to instantiate it from other classes too .

Private constructor means,"i dont let anyone create my instance except me ". So normally you would do this when you like to have a singleton pattern.

Following is the class in JDK which uses a private constructor .

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    // Don't let anyone else instantiate this class
    private Runtime() {
    }
}