can i have private constructor in my class?

India
May 14, 2007 11:02am CST
hey SCJPian. can anybody help me to know about Private constructor. and with the help of example can you show me how it works....?
3 responses
• India
5 Jun 07
Declaring a constructor private is perfectly fine. The java compiler will not complain. But like any other method declared private it will not be visible outside. Hence the class cannot be constructed outside with that particular constructor. Note: It cannot be accessed from the child clas using super eg class A { private A(){} } class B extends A { B() { super(); } } The above code will not compile. Try it. It is only useful in creating singleton classes and also in circumstances where child class is forced to make specific calls to certain constructors that are not private.
1 person likes this
@raghwagh (1528)
• India
20 May 07
Private constructors can be declared in a class and it has its own use also.Only if you declare a constructor as private then you cannot instantiate that class using that constructor. eg. class ABC{ private ABC(){} public ABC(int a){} } Then you can instantiate the class using, ABC a=new ABC(5); But you will not be able to instantiate a class with , ABC a=new ABC(); as in this case it will be calling the no parameter constructor and it is provate and hence not accessable.
1 person likes this
@senthil2k (1501)
• India
16 May 07
Yes.. Private constructor is perfectly fine in Java... Private Constructor prevents the Class being instantiated externally. The most common usage of the Private Constructor is in Singleton Classes (Classes that should have only one instance at any point of time). For eg., public class TestClass { private static TestClass t = new TestClass(); private TestClass(){ } public TestClass getInstance(){ return t; } } In the above class, to get the instance of the TestClass, you CANT call, TestClass xx = new TestCall(); THIS IS WRONG. You should only use TestClass xx = TestCall.getInstance(); Hope this clarifies.