Originally posted by amit taneja: in one of the interveiw i attended...
i have been asked can constructor have pvt access modifier.. ? and can we create class ?
i said yes we can have pvt constructor we can also create instance of that class which has pvt constructor but only in that class it self... i.e in the code of the same classs
is i m right...i think...
but my question is can we also create class if we instantiate that class in other class..
i know that class can not be inherited but can we instatiate that class as a associtation.. in other class ?
If all the constructors are private, then no, you cannot instantiate that class in another class. However, as the example above illustrates, you can use a factory method to create new instances. This is commonly seen in the Singleton pattern in order to ensure that only one instance of a class is available. If you want more information, you should google or search this message board for "Singleton". I think there is something in the FAQ about it, too.
hi my Dear friend i am also new to java i think that when we declare class with private Constructor in that case we cannot create instance of it take an example of Math class in it all the methods are Static so it is not necessary to create instance of it this facility can be provided by declaring Constructer Ptivate Math class has Private Construtor
Ganesh, That is correct. The class you are describing is know as a "utility class." In a utility class, you would not want people to instantiate it and would not provide a mechanism for doing so. In the above examples, you would as you want people to instatiate it - just not through the constructor.