为什么不能从构造函数是私有的类继承? [英] Why can you not inherit from a class whose constructor is private?
问题描述
为什么Java不允许从构造函数是私有的类继承?
Why does Java disallow inheritance from a class whose constructor is private?
推荐答案
Java不会阻止使用私有构造函数对类进行子类化。
Java doesn't prevent sub-classing of class with private constructors.
public class Main {
static class A {
private A() {
System.out.println("Subclassed A in "+getClass().getName());
}
}
static class B extends A {
public B() {
}
}
public static void main(String... ignored) {
new B();
}
}
打印
Subclassed A in Main$B
什么它可以防止无法访问其超类的任何构造函数的子类。这意味着私有构造函数不能在另一个类文件中使用,并且包本地构造函数不能在另一个包中使用。
What it prevents is sub-classes which cannot access any constructors of its super class. This means a private constructor cannot be used in another class file, and a package local constructor cannot be used in another package.
在这种情况下,你唯一的选择是代表团。您需要调用工厂方法来创建超级类的实例并将其包装起来。
In this situation, the only option you have is delegation. You need to call a factory method to create an instance of the "super" class and wrap it.
这篇关于为什么不能从构造函数是私有的类继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!