何时应将构造函数声明为公共,何时应将其声明为包私有?
在Java中,我有时看到构造函数声明为“public”,有时它没有访问修饰符,这意味着它是包私有的。在什么情况下我必须重复使用一个,反之亦然?
In Java I see sometimes the constructor declared as 'public' and sometimes it has no access modifier meaning it's package-private. What are the cases in which I must use one over the over and vice-versa?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题中包含着答案。如果您允许包外部的客户端代码实例化您的对象,请将构造函数公开。如果您不希望这样(因为对象是特定于包的或对象本身无法直接实例化),请使用包私有。
例如,如果您有一个应该使用
Car
(这是一个接口)的客户端代码,并且某些包com.company.cars
包含实现>Car
接口(BMW、WV、Opel
)等等,那么您宁愿有一个工厂来实例化必要的 Car 实现。因此,只有工厂才能访问构造函数。The question contains the answer. Make the constructor public if you allow your client code outside the package instantiate your object. If you don't want that( because object is package specific or the object itself can't be instantiated directly ) use package-private.
For example, if you have a client code that should use a
Car
( which is an interface ) and some packagecom.company.cars
contains classes, which implements theCar
interface(BMW, WV, Opel
) and so on, then you would rather have a factory which instantiates necessary Car implementation. So, only the factory would have access to the constructor.修饰符适用于构造函数,与字段和方法相同。
public
,则任何类都可以访问并查看它。私有
,则该类之外的任何其他类都无法访问或查看它。在文档中了解有关访问控制的更多信息
通常会创建构造函数
private
当您使用工厂模式或单例模式时Modifiers applies to constructor same as fields and method.
public
, any class can access and see it.private
, no other class outside that class can access or see it.Read more about access control at documentation
Generally constructors are made
private
when you use Factory pattern or Singleton pattern“Package private”(默认访问)尽管是默认设置,但除了外部类/接口/枚举之外很少是一个好的选择。它适用于具有一组固定子类(在同一包中)的抽象类,有点像同一枚举中的
enum
构造函数。如果外部类型是包私有的,您不妨将公共构造函数和成员保留为公共,而不是更奇特的访问修饰符。"Package private" (default access), despite being the default, is rarely a good choice other than on outer class/interface/enum. It would be appropriate for an abstract class with a fixed set of subclasses (in the same package), a bit like an
enum
constructor in the same enum. If the outer type is package private, you might as well leave public constructors and members public rather than a more exotic access modifier.