已知私有構造函數阻止在類之外創建實例。他們還說,它不允許打電話給超級玩家,因此它可以防止高速行駛。但是......現在看來似乎我可以創建多個實例,並可以調用超(或什麼是錯?):我不明白私人構造函數如何不能創建外部實例並防止子類化(儘管他這麼做了!)
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
同一個外部類中的類可以訪問私有成員。假設如果你這樣做了,你就知道你在做什麼,而你的左手並沒有試圖阻止你的右手進行編碼。 –