私有类的构造函数是否必须是私有的?

时间:2013-03-13 09:14:33

标签: java

如果一个类是私有的,那么构造函数也必须是私有的吗?

5 个答案:

答案 0 :(得分:4)

不,没有这样的限制。请参阅JLS §8.8.3. Constructor Modifiers

值得指出的是,只能声明一个嵌套类private。 JLS允许此类的构造函数使用任何有效的访问修饰符。

答案 1 :(得分:3)

如果您的意思是嵌套类,则答案为否。使内部类私有使它只能在外部类中使用。

编辑:外部类似乎可以完全访问内部类的内部,无论其访问修饰符如何。这使我的上述推理无效,但无论如何,都没有这样的限制。但奇怪的是,现在看来,如果内部类是private,它的构造函数本质上是 private,无论其访问修饰符如何,因为没有其他人可以调用它。

答案 2 :(得分:1)

不,没有。相反,如果使用私有构造函数(私有类的默认值)从外部类创建内部类的实例,Java将创建一个额外的类来防止访问冲突并保持JVM满意

如果你编译这个类

class Test {
    private class Test2 {
        Test2() {
        }
    }
    Test() {
        new Test2();
    }
}

javac将创建Test.class,Test @ Test2.class

如果你编译这个类

class Test {
    private class Test2 {
    }
    Test() {
        new Test2();
    }
}

javac将创建Test.class,Test @ Test2.class,Test $ 1.class

答案 3 :(得分:0)

不,它没有修复,您可以将其设置为私人/公共/任何您想要的。

但是在某些情况下,当你不想让其他类创建这个类的对象时,我更喜欢将构造函数设为私有。那么在这种情况下你可以通过设置构造函数私有来做这样的事情。

private class TestClass{
    private TestClass testClass=null;
    private TestClass(){
         //can not accessed from out side
         // so out side classes can not create object
         // of this class
    }

    public TestClass getInstance(){
      //do some code here to
      // or if you want to allow only one instance of this class to be created and used
      // then you can do this
      if(testClass==null)
           testClass = new TestClass();

      return testClass;
    }
}

顺便说一下,这取决于你的要求。

答案 4 :(得分:0)

不是私有的。但它可以。例如:

public class Outer {

    // inner class with private constructor
    private class Inner {
        private Inner() {
            super();
        }
    }

    // this works even though the constructor is private.
    // We are in the scope of an instance of Outer
    Inner i = new Inner();

    // let's try from a static method
    // we are not in the scope of an instance of Outer
    public static void main(String[] args) {

        // this will NOT work, "need to have Inner instance"
        Inner inner1 = new Inner();

        // this WILL work
        Inner inner2 = new Outer().new Inner();
    }
}

// scope of another class
class Other {
    // this will NOT work, "Inner not known"
    Inner inner = new Outer().new Inner(); 
}

如果在私有内部类上使用privatepublic构造函数,则没有任何区别。原因是内部类实例是外部类实例的一部分。这张图片说明了一切:

Inner class is part of the outer class. That's why all private members of the inner class can be accessed from the outer class.

请注意,我们所说的是内部类。如果嵌套类为static,则官方术语为静态嵌套类,这与内部类不同。只需调用new Outer.Inner()即可访问公共静态嵌套类而无需外部类实例。有关内部类和嵌套类的更多信息,请参见此处。 http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

相关问题