问题描述
我很感激这些问题的解释:
I would appreciate an explanation for these questions:
- 我们可以
覆盖
Java中的构造函数? -
构造函数
可以是私有的吗?
- Can we
Override
a constructor in Java? - Can a
Constructor
be private?
推荐答案
不,你不能覆盖构造函数。他们不是遗传的。但是,每个子类构造函数必须将 链接到子类或中的另一个构造函数到超类中的构造函数。例如:
No, you can't override a constructor. They're not inherited. However, each subclass constructor has to chain either to another constructor within the subclass or to a constructor in the superclass. So for example:
public class Superclass
{
public Superclass(int x) {}
public Superclass(String y) {}
}
public class Subclass extends Superclass
{
public Subclass()
{
super(5); // chain to Superclass(int) constructor
}
}
含义不被继承的构造函数是不能执行此操作:
The implication of constructors not being inherited is that you can't do this:
// Invalid
Subclass x = new Subclass("hello");
至于你的第二个问题,是的,构造函数可以是私有的。它仍然可以在类或任何封闭类中调用。这对于单身人士来说很常见:
As for your second question, yes, a constructor can be private. It can still be called within the class, or any enclosing class. This is common for things like singletons:
public class Singleton
{
private static final Singleton instance = new Singleton();
private Singleton()
{
// Prevent instantiation from the outside world (assuming this isn't
// a nested class)
}
public static Singleton getInstance() {
return instance;
}
}
私人构造函数也用于防止任何实例化,如果你有一个只有静态方法的实用程序类。
Private constructors are also used to prevent any instantiation, if you have a utility class which just has static methods.
这篇关于我们可以覆盖Java中的构造函数,并且构造函数可以是私有的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!