| Author |
constructor private ?
|
samdeep aarzoo
Ranch Hand
Joined: Jun 09, 2005
Posts: 160
|
|
can we make constructor private is it legal to make constructor private
|
 |
Richard Anderson
Ranch Hand
Joined: May 20, 2005
Posts: 61
|
|
Yes, you can make your contructor private; this is typically what you do when implementing the Singleton pattern. Example: public class MyClass { private MyClass myInstance = null; private MyClass() { } public static MyClass getInstance() { if (myInstance == null) { myInstance = new MyClass; } return myInstance; } } And to use, put the following in your main method: MyClass myClass = MyClass.getInstance(); Notice that you call getInstance() instead of "new MyClass()", which you wouldn't be able to do without a compiler error. -Rich, SCJP
|
-Rich, SCJP 1.4
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9956
|
|
|
It is also used anytime you don't want anybody to be able to instantiate your class. Utility classes come to mind, like the Math class... all the useful methods are static, so you don't NEED to create an instance.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
Another pattern where it's used is the Typesafe Enum pattern, where the only instances are static final fields inside the class itself.
|
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
|
 |
 |
|
|
subject: constructor private ?
|
|
|