This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
only public or default can apply to class, but what about a class with private constructor? I tried it and seems it is not accessible outside of class. If so, what is this class for? useless? Please help me out. Thanks for reply.
You can make the constructer private, if you don't want others to create any objects of that class. It doesn't mean that the class is useless. For example the java.lang.Math class has a private constructer, but still we can use it (with out creating any objects). Also, making constructers private is one approach to implement Singleton pattern.
Some classes have special static methods that will create an object of the same class for the caller. These are known as factory methods. Only the factory method is allowed to construct an object of the class, so in this case the constructor would be made private to the class. [ October 07, 2004: Message edited by: Barry Gaunt ]
Originally posted by Jeroen Wenting: Having only private constructors to a class will also make sure the class can never be subclassed. This is a good way to enforce limitations to inheritance.
The standard way, though, is to simply declare the class as final.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
The correct way is both. A class with a private ctor is implicitly unsubclassable. An acknowledgement of this design decision by explicitly declaring the class 'final' is warranted. Most style checkers (that I know) of will pick this one up.
"classes are public or default". For the purposes of the exam, it might pay to point out that "top-level classes are public or default". Nested classes can be and one of the four access scopes.
We can also use private constructor in class when we want to implement Singleton Design Pattern(Only one instance of that particular class).
Joined: Sep 24, 2003
A more general statement might be "A private constructor allows control over the construction of instances". The Factory and Singleton demand control over the construction of instances, as do many other design patterns.