m_pGladiator
m_pGladiator

Reputation: 8620

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?

Upvotes: 22

Views: 11384

Answers (2)

Denis R.
Denis R.

Reputation: 818

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.

Upvotes: 4

user8681
user8681

Reputation:

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.

Upvotes: 32

Related Questions