Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we declare a public constructor when the class is declared as package private?

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?

like image 707
m_pGladiator Avatar asked Oct 28 '08 13:10

m_pGladiator


People also ask

Can you have a public constructor in a private class?

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 .

Should you declare constructor public?

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.

Should a class constructor be public or private?

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.

Can we declare constructor as public/private protected?

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.


2 Answers

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.

like image 71
Jorn Avatar answered Oct 21 '22 00:10

Jorn


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.

like image 42
Denis R. Avatar answered Oct 20 '22 23:10

Denis R.