+ 3
Can constructors be declared private in java? If yes what is the use?
3 ответов
+ 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
+ 2
thanks a lot @Davye.
+ 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