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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/243218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:36:18  来源:igfitidea点击:

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

javacoding-style

提问by m_pGladiator

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?

我认为在这种情况下不需要声明公共构造函数,因为无论如何都不能在包外访问该类。但是当该类只有包私有构造函数时是否有一些隐藏的影响?

回答by Jorn

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.

不,您不必声明公共构造函数;包私有构造函数将同样可用。包外的类无论如何都不能使用构造函数,因为它们看不到类。

回答by Denis R.

If your class is package private then the access levels indicated by the modifier keyword publictogether with the default package privateaccess 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. 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.

但是,您可以指明您希望该方法具有的行为,以防在开发过程中更改类的可见性。当您打开一些以前是内部的 API 时,可能会发生这种情况。在这种情况下,将构造函数声明为包私有看起来更保守,因为您不会同时打开所有门。