61

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.

Dhanuka
  • 2,826
  • 5
  • 27
  • 38
Hash Leon
  • 564
  • 1
  • 5
  • 11
  • 4
    @George Stocker The title is a duplicate, I agree. But the question is really "why would I want to declare a private constructor?" In that case, only the least upvoted answer in the duplicate answers this question, and only tangentially. – Teepeemm Jun 25 '15 at 14:29
  • 1
    @HashLeon I asked you to narrow down your question; your first question is the duplicate of the one I closed it as, and your second question is a duplicate of this question: http://stackoverflow.com/questions/17342815/what-is-the-use-of-private-constructor-in-java – George Stocker Jun 25 '15 at 18:39

11 Answers11

95

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.

Community
  • 1
  • 1
Dhanuka
  • 2,826
  • 5
  • 27
  • 38
  • 1
    Good answer, but feel like it might be enhanced by an example of when private constructors are useful. E.g. factory methods: http://jlordiales.me/2012/12/26/static-factory-methods-vs-traditional-constructors/ – Tom Wright Jun 23 '15 at 07:10
  • 7
    @TomWright It's not so much factory methods, but the [builder pattern](https://en.wikipedia.org/?title=Builder_pattern) that often makes use of private constructors. – Ted Hopp Jun 23 '15 at 07:34
  • 2
    A `private` constructor does not only serve singletons. It serves all kind of use patterns where the implementation wants to have full control over the instance creation. Note that all `enum`s have implicitly `private` constructors… – Holger Jun 23 '15 at 07:48
  • `default` constructor means every class in same package can create instances of this class. Very useful for unit tests (same package but different source folder or project). SWT uses a lot of `default`components (constructors, methods, etc.) because only SWT objects/classes should (must) have access to theses ones (and you can have a access if you have declared the good package). – Max Jun 23 '15 at 07:55
  • 5
    Your implementation of `getInstance() { if(database == null) { database = new Database(); } return database; }` is not thread-safe: two (or more) threads may create their own instances of `Database`, and may finally use the same or different instances, depending on the exiting order. – CiaPan Jun 23 '15 at 11:11
  • A constructor can have any of the access modifier depending on the requirement. – Harshit Gupta Jun 23 '15 at 12:28
  • 1
    It's worth mentioning that a singleton is considered an anti-pattern by many - so be extra careful when you consider it. – Benjamin Gruenbaum Jun 23 '15 at 14:10
  • 4
    @CiaPan the entire `getInstance()` method is synchronized, so it will block duplicate callers until the first completes, ensuring only a single instance of `Database` is created. – SnakeDoc Jun 23 '15 at 16:08
  • Everybody seems to be using the singleton as an example of private constructors, and while it is a good example, the Builder Pattern is probably better since it makes use of both private and public constructors. – SnakeDoc Jun 23 '15 at 16:09
  • @SnakeDoc Oh, you're right. I must have missed `synchronized` in the declaration. – CiaPan Jun 23 '15 at 20:42
  • I agree with @TedHopp. People here usually mention Singletone as the main use of private constructors. But in my experience you most likely will see private constructor in builder classes (as in "Efective Java" Item 2) or (and this even more often) in Helper classes which have only static methods. – nkukhar Jul 09 '15 at 17:57
14

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.

steinar
  • 9,383
  • 1
  • 23
  • 37
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • 8
    Note that this is not threadsafe. – questionaire Jun 23 '15 at 07:09
  • 1
    Besides that the declaration of “isntance” won’t match the referenced “instance”, this code doesn’t work as the variable is not `static`. Obviously, you never tried to compile that. Further, it’s pointless. Since classes are initialized on their first actual use, there is no need for this kind of lazy creation. Just write `private static final Ex instance = new Ex();` and `public static Ex getInstance() { return instance; }` and this field will become initialized when `getInstance()` is called for the first time. Then, it’s even thread-safe. – Holger Jun 23 '15 at 07:45
  • 1
    sorry missed the static code for instance variable, added it now. – Anand S Kumar Jun 23 '15 at 08:07
7

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

Alp
  • 3,027
  • 1
  • 13
  • 28
5

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() {
    }
}
Aston Ray
  • 109
  • 7
  • Actually, a private constructor means "I don't let anyone create my instance _in this way_ except me." A class can easily have a mix of constructors with different access specifiers. – Ted Hopp Jun 23 '15 at 07:37
  • Hey Ted ,absolutely right .i mean to say If only there is a private constructor .Thanks for the point :) – Aston Ray Jun 23 '15 at 08:11
5

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

Nitesh Soomani
  • 572
  • 5
  • 12
4

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.

A.v
  • 734
  • 5
  • 26
4

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.

Marc Giombetti
  • 819
  • 1
  • 8
  • 20
  • 2
    That’s still completely unnecessary. Just write `private static Singleton instance = new Singleton();` and forget about the `null`-checks and `synchronized`. Classes are initialized on their first use and hence it is already implied that the field will become initialized when `getInstance()` is invoked for the first time. That’s lazy and thread-safe—for free. – Holger Jun 23 '15 at 08:02
  • Oh and by the way, you code is **not** thread-safe, it’s the double-checked locking anti-pattern. Without declaring the variable `instance` as `volatile` it doesn’t work. – Holger Jun 23 '15 at 08:06
  • Dear Holger, thanks for your comment! You are right: `volatile` was missing! The implementation i suggested still allows you to initialize sth in the constructor. I used if to initialize values into a cache, since I was using the singleton to cache resources. – Marc Giombetti Jun 23 '15 at 08:42
  • Of course, you can do things in the constructor. That doesn’t change the fact that the manual lazy instantiation within `getInstance()` is unnecessary. Just write `private static Singleton instance = new Singleton();` and it will still be executed *on the first invocation* of `getInstance()`. As said, classes are initialized lazily anyway. – Holger Jun 23 '15 at 08:55
3

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.

Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63
  • I agree that they *should* but saying they *have* to be may be a stretch. – Captain Man Jun 23 '15 at 13:51
  • Why would you want the constructor to be public in a factory class? – Arthur Eirich Jun 23 '15 at 14:44
  • I didn't say I'd want it to be, I was just saying it didn't have to be. I agree that it should though. It will compile and it will run and if someone makes an instance of it it's not necessarily even the end of he world, because of that I don't think it's right to say it **must** be. – Captain Man Jun 23 '15 at 15:32
  • Saying **must** I did not meant that it is a law, I just wanted to point that by design it is correct. Of course instantiating a factory class would be possible, but it would violate the factory pattern. I do not insist on my rightness or so, I can easily edit my answer :) – Arthur Eirich Jun 23 '15 at 19:22
  • 1
    I believe what we have here is merely a differing usage of **must**, to me **must** means it's absence will cause it to not run or compile correctly, to you **must** means it's absence is not correctly adhering to the pattern, and that's okay. :) – Captain Man Jun 23 '15 at 19:25
1

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.

Rick Smith
  • 9,031
  • 15
  • 81
  • 85
Nimishan
  • 19
  • 1
1

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

Teepeemm
  • 4,331
  • 5
  • 35
  • 58
1

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.

supercat
  • 77,689
  • 9
  • 166
  • 211