Can constructors be declared private in java? If yes what is the use? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can constructors be declared private in java? If yes what is the use?

7th May 2017, 6:04 AM
Parth Prashar
Parth Prashar - avatar
3 Answers
+ 19
Yes, a constructor can be private and a private constructor can be overloaded also. Following program illustrates. public class Test {   private Test()   {     System.out.println("I am default private constructor");   }   private Test(int x)   {     System.out.println("I am overloaded private constructor. " +x)   }   public static void main(String args[])   {             Test t1 = new Test();     Test t2 = new Test(10);   } } There are two uses of a private constructor. 1. Composition (or has-a relationship) is not possible with default constructor. That is, you cannot create an object of the class in another class with default constructor. 2. The class with private constructor is not fit for inheritance. That is, the class cannot be extended. The above two statements are proved programmatically hereunder. :-D
7th May 2017, 6:13 AM
Dev
Dev - avatar
+ 2
thanks a lot @Davye.
7th May 2017, 6:16 AM
Parth Prashar
Parth Prashar - avatar
+ 2
an use case are singletons. you make a public static method to instantiate and access the single instance of your class. eg license handling, access to a single physical device, ... https://code.sololearn.com/cQsAcUted9IO/?ref=app
7th May 2017, 6:51 AM
Volker Milbrandt
Volker Milbrandt - avatar