我不明白私有构造函数如何不能在外部创建实例并阻止子类化(当他这样做时!)
I don't understand how private constructor can't create instances outside and prevents subclassing (while he doing all that!)
众所周知,私有构造函数会阻止在 class 之外创建实例。他们还说它阻止了 sublcassing,因为它不允许调用 super。但是......似乎我可以创建多个实例并可以调用 super (或者有什么问题?):
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
构造函数 B 3B 4
你在同一个 class/file (TestPrivate class) 的主方法中做 test.new A();
,没有理由你不能访问所有方法,包括私有方法一个....
private
访问方式,可以在整个Class
范围内访问。由于 Class B 在 Class A 中,Class B 将被视为Class 并且可以自由访问 A
的构造函数
如果你有一个look at docs,明确提到。
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
您正在使用内部 类。这意味着 A
和 B
都是 TestPrivate
.
的成员
JLS 表示(当声明成员或构造函数时 private
):
access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
因此,在 TestPrivate
.
的正文中,允许 访问任何成员的私有成员和私有构造函数
众所周知,私有构造函数会阻止在 class 之外创建实例。他们还说它阻止了 sublcassing,因为它不允许调用 super。但是......似乎我可以创建多个实例并可以调用 super (或者有什么问题?):
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 构造函数 B 3B 4
你在同一个 class/file (TestPrivate class) 的主方法中做 test.new A();
,没有理由你不能访问所有方法,包括私有方法一个....
private
访问方式,可以在整个Class
范围内访问。由于 Class B 在 Class A 中,Class B 将被视为Class 并且可以自由访问 A
如果你有一个look at docs,明确提到。
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
您正在使用内部 类。这意味着 A
和 B
都是 TestPrivate
.
JLS 表示(当声明成员或构造函数时 private
):
access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
因此,在 TestPrivate
.