The very first question asked about private designers in an interview:
Can we have a private constructor in the class?
And sometimes the candidate gives the answer: no, we cannot have private designers.
So I would like to say: yes, you can have private constructors in the class.
This is not a special thing, try to think so
Private: everything that is private is accessible only from the class.
Constructor: a method whose name matches the name of the class, and it is implicitly called when the class object is created.
or you can say that to create an object you need to call its constructor, if the constructor is not called, then the object cannot be created.
This means that if we have a private constructor in the class, then its objects can only be created inside the class. Thus, in simple terms, if the constructor is private, you cannot create its objects outside the class.
What are the benefits? This concept can be implemented to achieve a singleton object (this means that only one class object can be created).
See the following code,
class MyClass{ private static MyClass obj = new MyClass(); private MyClass(){ } public static MyClass getObject(){ return obj; } } class Main{ public static void main(String args[]){ MyClass o = MyClass.getObject();
Now the tricky part is why you made a mistake, as explained in other answers, you can get around the limitation using Reflection.
gprathour Jun 23 '14 at 10:24 2014-06-23 10:24
source share