有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (2) 个答案

  1. # 1 楼答案

    您正在同一类/文件(TestPrivate类)内的主方法中执行test.new A();,没有理由不能访问所有方法,包括私有方法

  2. # 2 楼答案

    private访问意味着,你可以在整个Class内访问。由于类B位于类A内部,因此类B将被视为类的成员,可以自由访问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.