java 什么时候应该将构造函数声明为 public,什么时候应该将其声明为包私有的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4562304/
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
When should a constructor be declared public and when should it be package-private?
提问by Jon
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?
在 Java 中,我看到有时构造函数声明为“public”,有时它没有访问修饰符,这意味着它是包私有的。在什么情况下我必须使用一个,反之亦然?
回答by Vladimir Ivanov
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.
问题包含答案。如果您允许包外的客户端代码实例化您的对象,则将构造函数设为公开。如果您不希望那样(因为对象是特定于包的或对象本身无法直接实例化),请使用 package-private。
For example, if you have a client code that should use a Car
( which is an interface ) and some package com.company.cars
contains classes, which implements the Car
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.
例如,如果您有一个客户端代码应该使用 a Car
(它是一个 interface )并且某些包com.company.cars
包含实现Car
interface( BMW, WV, Opel
) 等的类,那么您宁愿拥有一个实例化必要的 Car 实现的工厂。因此,只有工厂才能访问构造函数。
public CarFactory {
public Car getCar(CarType carType) {
Car result = null;
switch(carType) {
case BMW:
result = new BMW();
case Opel:
result = new Opel();
}
return result;
}
}
class BMW implements Car {
// package-private constructor
BMW();
}
回答by Jigar Joshi
Modifiers applies to constructor same as fields and method.
修饰符适用于与字段和方法相同的构造函数。
- If it is
public
, any class can accessand seeit. - If it is
private
, no other class outside that class can accessor seeit.
- 如果是
public
,则任何类都可以访问并查看它。 - 如果是
private
,则该类之外的任何其他类都无法访问或查看它。
Read more about access control at documentation
Generally constructors are made private
when you use Factory pattern or Singleton pattern
通常private
在使用工厂模式或单例模式时会 创建构造函数
回答by Tom Hawtin - tackline
"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.
“包私有”(默认访问),尽管是默认值,但除了外部类/接口/枚举之外很少是一个好的选择。它适用于具有一组固定子类(在同一个包中)的抽象类,有点像enum
同一个枚举中的构造函数。如果外部类型是包私有的,则最好将公共构造函数和成员保留为公共而不是更奇特的访问修饰符。