已知私有构造函数阻止在类之外创建实例。他们还说,它不允许打电话给超级玩家,因此它可以防止高速行驶。但是......现在看来似乎我可以创建多个实例,并可以调用超(或什么是错?):我不明白私人构造函数如何不能创建外部实例并防止子类化(尽管他这么做了!)
public class TestPrivate {
private static int i;
class A {
private String s = "Constructor ";
private A() {
print();
}
void print() {
s += getClass().getSimpleName() + " " + ++i;
System.out.println(s); }
}
class B extends A {
B() {
super(); // <--- i can call super
super.print();
}
}
public static void main(String[] args) {
TestPrivate test = new TestPrivate();
// creating multiple objects with private constructors
test.new A();
test.new A(); // <--- i can call constructor outsised the class many times
test.new B();
}
}
输出: 构造A 1 构造A 2 构造函数b 3分配 构造乙3B 4
为'A'和'B'类创建不同的文件,私人不阻止像这样的内部类访问 – AxelH
同一个外部类中的类可以访问私有成员。假设如果你这样做了,你就知道你在做什么,而你的左手并没有试图阻止你的右手进行编码。 –