简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM