I think in this case there is no need to declare a public constructor since the class is not accessible outside the package anyway. But is there some hidden impact when the class has only package private constructor?
The private class can't be extended by classes outside of the package, so protected has no use either. Even when using reflections, a public constructor is not accessible by default from other packages and will throw a IllegalAccessException .
Constructors in programming are the methods that are called automatically when an object is initialized. The constructor's purpose is to initialize the object. Constructors should always be public and they are declared without any return type.
There is no rule that constructor to be public . Generally we define it public just because we would like to instantiate it from other classes too . Private constructor means,"i dont let anyone create my instance except me ". So normally you would do this when you like to have a singleton pattern.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class.
No, you don't have to declare the public constructor; package private constructors will be just as usable. Classes outside the package wouldn't be able to use the constructor anyway, since they can't see the class.
If your class is package private then the access levels indicated by the modifier keyword public
together with the default package private access level of the constructor are equivalent.
You can however indicate the behavior you intent the method to have in case the class visibility is changed during development. This may happen when you open some APIs which were previously internal. In that case it looks more conservative to declare the constructor as package private since you do not open all doors at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With