Do constructors always have to be public?

JavaOopDesign PatternsConstructorAccess Modifiers

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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

Solution 4 - Java

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() {
	}
}

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

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.)

Solution 11 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHash LeonView Question on Stackoverflow
Solution 1 - JavaDhanukaView Answer on Stackoverflow
Solution 2 - JavaAnand S KumarView Answer on Stackoverflow
Solution 3 - JavaAlpView Answer on Stackoverflow
Solution 4 - JavaAston RayView Answer on Stackoverflow
Solution 5 - JavaNitesh SoomaniView Answer on Stackoverflow
Solution 6 - JavaA.vView Answer on Stackoverflow
Solution 7 - JavaMarc GiombettiView Answer on Stackoverflow
Solution 8 - JavaArthur EirichView Answer on Stackoverflow
Solution 9 - JavaNimishanView Answer on Stackoverflow
Solution 10 - JavaTeepeemmView Answer on Stackoverflow
Solution 11 - JavasupercatView Answer on Stackoverflow