java我不明白私有构造函数如何不能在外部创建实例并阻止子类化(而他却在这么做!)
众所周知,私有构造函数阻止在类之外创建实例。他们还说,它可以防止再分类,因为它不允许调用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 建造师B3 建造师B 3B 4
# 1 楼答案
您正在同一类/文件(TestPrivate类)内的主方法中执行
test.new A();
,没有理由不能访问所有方法,包括私有方法# 2 楼答案
private
访问意味着,你可以在整个Class
内访问。由于类B位于类A内部,因此类B将被视为类的成员,可以自由访问A
的构造函数如果你有一个look at docs,它会被清楚地提到