[英]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. 如果您的类是包私有,则修饰符关键字public
指示的访问级别与构造函数的默认包私有访问级别是等效的。
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. 当您打开以前内部的一些API时,可能会发生这种情况。 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. 在这种情况下,将构造函数声明为包私有看起来更为保守,因为您不会同时打开所有门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.