Java 构造函数总是必须是公共的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30995942/
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
Do constructors always have to be public?
提问by Hash Leon
My first question is -
我的第一个问题是——
class Explain() {
public Explain() {
}
}
Should Constructor always declared as public?
构造函数应该始终声明为公共吗?
What if I create a private
constructor.
如果我创建一个private
构造函数会怎样。
I always seen constructors are implicitly public
. So why private
constructor is useful? Or is it not useful at all. Because nobody could ever call it, or never make an object(because of the private
constructor) ! And that is my second question.
我总是看到构造函数是隐式的public
。那么为什么private
构造函数有用呢?或者它根本没有用。因为没有人可以调用它,或者永远不会创建对象(因为private
构造函数)!这是我的第二个问题。
采纳答案by Dhanuka
No, Constructorscan be public
, private
, protected
or default
(no access modifier at all).
不,构造函数可以是public
, private
,protected
或default
(根本没有访问修饰符)。
Making something private
doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private
constructor is useful too.
制作一些东西private
并不意味着没有人可以访问它。这只是意味着班级以外的任何人都无法访问它。所以private
构造函数也很有用。
One of the use of private
constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private
constructor we can ensure that no more than one object can be created at a time.
private
构造函数的用途之一是为单例类提供服务。单例类是一种将对象创建的数量限制为一个的类。使用private
构造函数,我们可以确保一次创建的对象不超过一个。
Example -
例子 -
public class Database {
private static Database singleObject;
private int record;
private String name;
private Database(String n) {
name = n;
record = 0;
}
public static synchronized Database getInstance(String n) {
if (singleObject == null) {
singleObject = new Database(n);
}
return singleObject;
}
public void doSomething() {
System.out.println("Hello StackOverflow.");
}
public String getName() {
return name;
}
}
More information aboutaccess modifiers.
回答by Anand S Kumar
Yes , Constructors can have any access specifier/access modifier.
是的,构造函数可以有任何访问说明符/访问修饰符。
Private constructors are useful for creating singleton
classes.
私有构造函数对于创建singleton
类很有用。
Singleton- A singleton class is a class where only a single object can be created at runtime (per JVM) .
单例- 单例类是在运行时只能创建一个对象的类(每个 JVM)。
A simple example of a singleton class is -
单例类的一个简单示例是 -
class Ex {
private static Ex instance;
int a;
private Ex() {
a = 10;
}
public static Ex getInstance() {
if(instance == null) {
instance = new Ex();
}
return instance;
}
}
Note, for the above class, the only way to get an object (outside this class) is to call the getInstance() function, which would only create a single instance and keep returning that.
请注意,对于上述类,获取对象(在该类之外)的唯一方法是调用 getInstance() 函数,该函数只会创建一个实例并不断返回该实例。
Also, note that this is not thread-safe.
另外,请注意这不是线程安全的。
回答by Alp
Constructors could be public, default or private and it all depends on what you want to do with it.
构造函数可以是公共的、默认的或私有的,这完全取决于您想用它做什么。
For example, if you are defining a Singleton class, you'd better hide(meaning making it private so that it is only available to the class where it belongs) the constructor to prevent other classes to instantiate your class at their will.
例如,如果您正在定义一个 Singleton 类,您最好隐藏(意味着将其设为私有,以便它仅对它所属的类可用)构造函数以防止其他类随意实例化您的类。
You may want to declare it default, let's say, for testing purposes so that test cases within the same package could access it.
您可能希望将其声明为默认值,比方说,出于测试目的,以便同一包中的测试用例可以访问它。
More detailed info could be found here
更详细的信息可以在这里找到
回答by A.v
Constructors can have all kind of access modifiers. The usage of different access modifier on constructors are different.
构造函数可以有各种访问修饰符。不同的访问修饰符在构造函数上的使用是不同的。
You make a constructor public
if you want the class to be instantiated from any where.
public
如果您希望从任何位置实例化该类,您可以创建一个构造函数。
You make a constructor protected
if you want the class to be inherited and its inherited classes be instantiated.
protected
如果您希望继承该类并实例化其继承的类,则可以创建一个构造函数。
You make a constructor private
if you want the class to be instantiated just from its own members usually a static block or static method. It means that you take control of instantiating the class and apply some rule on instantiation. Example of usage of private constructor is singleton design pattern.
private
如果您希望类仅从它自己的成员(通常是静态块或静态方法)中实例化,则可以创建一个构造函数。这意味着您可以控制类的实例化并在实例化上应用一些规则。私有构造函数的使用示例是单例设计模式。
回答by Arthur Eirich
A constructor hasto be at least protected or even private while creating, for example, custom factory classes, like:
例如,在创建自定义工厂类时,构造函数必须至少是受保护的甚至是私有的,例如:
public final class MyFactory {
private MyFactory(){} // this one prevents instances of your factory
}
public static void doSomething(){} // access that with MyFactory.doSomething
Note that this is only one example showing when a constructor shouldn't be public.
请注意,这只是一个示例,说明何时不应公开构造函数。
回答by Aston Ray
There is no rule that constructor to be public .Generally we define it public just because we would like to instantiate it from other classes too .
没有规定构造函数是公共的。通常我们将它定义为公共只是因为我们也想从其他类中实例化它。
Private constructor means,"i dont let anyone create my instance except me ". So normally you would do this when you like to have a singleton pattern.
私有构造函数的意思是,“除了我,我不允许任何人创建我的实例”。所以通常当你喜欢单例模式时你会这样做。
Following is the class in JDK which uses a private constructor .
以下是 JDK 中使用私有构造函数的类。
public class Runtime {
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
// Don't let anyone else instantiate this class
private Runtime() {
}
}
回答by Nitesh Soomani
No,Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)
不,构造函数可以使用任何访问修饰符,包括私有。(私有构造函数意味着只有类本身内的代码才能实例化该类型的对象,因此如果私有构造函数类想要允许使用类的实例,则该类必须提供允许访问的静态方法或变量从类中创建的实例。)
Example
例子
class Alpha {
static String s = " ";
protected Alpha() { s += "alpha "; }
}
class SubAlpha extends Alpha {
private SubAlpha() { s += "sub "; }
}
public class SubSubAlpha extends Alpha {
private SubSubAlpha() { s += "subsub "; }
public static void main(String[] args) {
new SubSubAlpha();
System.out.println(s);
}
}
Output of above program will be
上述程序的输出将是
alpha subsub
阿尔法子子
回答by Marc Giombetti
I agree with the previous answers that a Singleton is a good example of a class having a private constructor. I would though recommend a different implementation: a thread safe Singleton:
我同意之前的答案,即单例是具有私有构造函数的类的一个很好的例子。不过我会推荐一个不同的实现:一个线程安全的单例:
/**
* Thread safe singleton
*/
public class Singleton {
private static volatile Singleton instance = null;
/**
* Private constructor
*/
private Singleton() {
}
/**
* Gets the Instance of the Singleton in a thread safe way.
* @return
*/
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Using a singleton in a thread safe way will safe you a lot of pain in parallel code.
以线程安全的方式使用单例可以让你在并行代码中避免很多痛苦。
回答by Nimishan
The simple explanation is if there is no constructor in a class, the compiler automatically creates a default constructor.
简单的解释是,如果类中没有构造函数,编译器会自动创建一个默认构造函数。
The constructor is not always declared as public, it can also be private, protected, or default.
构造函数并不总是声明为公共的,它也可以是私有的、受保护的或默认的。
The private constructors prevent a class from fully and clearly expressed/represented by its callers. In that case private constructors are useful. And if if we do not need our class to be sub-classed, we can use private constructors.
私有构造函数阻止一个类被它的调用者完全清楚地表达/表示。在这种情况下,私有构造函数很有用。如果我们不需要我们的类被子类化,我们可以使用私有构造函数。
回答by Teepeemm
Most of these answers refer to a singleton or factory class. Another time a private constructor appears is (for example) in the java.lang.Math class, where everything is static and no one should ever call the constructor (including the class itself). By having the private constructor, you prevent anyone outside the class from calling the constructor. (This doesn't prevent someone inside the class from calling the constructor, but then they're breaking their own rule.)
这些答案中的大多数是指单例或工厂类。另一次出现私有构造函数是(例如)在java.lang.Math 类中,其中一切都是静态的,任何人都不应该调用构造函数(包括类本身)。通过拥有私有构造函数,您可以防止类之外的任何人调用构造函数。(这不会阻止类中的某个人调用构造函数,但是他们违反了自己的规则。)