Hi all I had a confusion regarding private constructors. Supposing i define a class Test whose constructor is made private is it legal to instantiate a class like this Test t = new Test(); shouldn't this give a compile error. thanks
Hi Vidya Anything declared as private is accessible only to that class. Going by this definition you can use the constructor of this class in the class itself but not outside the class. Hence your code would work if it is inside the class where the private constructor is.
Hi Vidya, It is legal to instantiate a class having a private constructor as it's only constructor. The catch is where you can instantiate the class. You can instantiate such a class in the class itself & nowhere else. So,
is fine if it is somewhere in the Test class itself & it will result in a compiler error if it is outside the Test class. HTH Ashish Hareet
This private constructors are usefull when your creating a Singleton class: this way only the class itself may create the instance and make sure there is only one. regards. Carlos Olmos.