-1

如果我们在类中有一个私有构造函数会发生什么?(在 Java 中)

4

4 回答 4

3

这意味着(没有反射)构造函数将无法在您的类之外访问,因此其他类将无法调用它。只有您班级的成员才能创建其对象。

class A{
    private A(){} //private constructor

    private static A a = new A(); //you can create A object as a field

    void test(){
        new A(); // you can create A object inside methods of your class
    }

    class Inner{ // inner classes are also members of outer class so you can use 
                 // A constructor here
        A a = new A(); //OK
        void test(){
            new A(); //OK
        }
    }
}

class B{
    A a = new A();//error: we don't have access to A constructor
}
于 2013-03-16T10:25:30.323 回答
2

您只能在当前类中使用该构造函数。

于 2013-03-16T10:08:17.190 回答
0

您将只能从类中的其他构造函数或类中的静态方法调用它。

于 2013-03-16T10:06:33.970 回答
0

这通常是限制从此类创建对象的一种方式。这意味着您不能从类中创建对象。

于 2013-03-16T10:10:05.010 回答