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

假如想象 提交于 2020-01-09 07:42:12

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/243218/should-we-declare-a-public-constructor-when-the-class-is-declared-as-package-pri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!