简体   繁体   English

当类被声明为包私有时,我们应该声明一个公共构造函数吗?

[英]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.

相关问题 什么时候应该将构造函数声明为public,何时应该是package-private? - When should a constructor be declared public and when should it be package-private? 私有内部类的构造函数应该声明为public还是private? - Should the constructor of a private inner class be declared public or private? Java用Package Private Constructor继承公共类 - Java Inheriting a public class with Package Private Constructor 使用公共构造函数 Java 声明一个私有 static 嵌套 class? - Declare a private static nested class with a public constructor Java? 使用在公共 class 中声明的 class 成员定义的 getter/setter 将变量声明为私有是否有意义? - Does it make sense to declare variables as private with getters/setters for class member definitions declared within a public class? 包私有类中的公共成员 - Public members in package private class 什么时候应该在Java接口中声明CLASS? - when should we declare a CLASS inside an INTERFACE in java? 通过另一个包的公共子类使用包私有类的公共方法引用时出现IllegalAccessError - IllegalAccessError when using a public method reference of a package-private class through a public subclass from another package Class 是公开的,应在名为 .java 的文件中声明 - Class is public, should be declared in a file named .java 在公共类中使用包私有类 - Use package-private class in the public class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM