"Private Constructors" - What's that for?

I read a sentence from a book, saying that "Suppose that you want to create a class but you don't want it to be instantiated as an object. Just declear the class's constructors as private."

It's out of my imagination. What's the real user case for this weird "Private Consturctor"? Who knows?

Thanks.

CL

[332 byte] By [calvinla] at [2007-11-27 5:12:22]
# 1
If a class only has static methods, there is no need to make an instance of it. Take the java.lang.Math class, for example.
prometheuzza at 2007-7-12 10:33:11 > top of Java-index,Java Essentials,New To Java...
# 2

> It's out of my imagination. What's the real user case

> for this weird "Private Consturctor"? Who knows?

since a private constructor can at most be invoked from within its own class, the use is obviously to restrict instantiation to the own class

there are at least two usages for this:

1) you don't want the class to be instantiated at all (a helper class with only statics)

2) you want it to be instantiated but you want to control/limit this through other means like a static factory method, singleton accessor, ...

OnBringera at 2007-7-12 10:33:11 > top of Java-index,Java Essentials,New To Java...
# 3
Private constructer is normally used to implement singaltan pattern
m_k_ma at 2007-7-12 10:33:11 > top of Java-index,Java Essentials,New To Java...
# 4
Got it. Thanks guys!So many interesting stuffs...
calvinla at 2007-7-12 10:33:11 > top of Java-index,Java Essentials,New To Java...
# 5

public class TestFact {

private TestFact() {}

public static TestFact makeTestFact(String s) {

if ("Dog".equals(s)) {

return new Dog();

}

if ("Cat".equals(s)) {

return new Cat();

}

return null;

}

protected String whatever() {

return "foo";

}

private static class Dog extends TestFact {

public String toString() {

return whatever() + " dog";

}

}

private static class Cat extends TestFact { }

}

I must be really bored at work today...

paulcwa at 2007-7-12 10:33:11 > top of Java-index,Java Essentials,New To Java...
# 6
I use private constructors in enums that I want to contain some type of data. Not sure if that's the best practices approach in the field, but it seems to work pretty well.
JJCoolBa at 2007-7-12 10:33:11 > top of Java-index,Java Essentials,New To Java...