"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]

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