[英]Does a constructor of private class has to be private?
如果一个类是私有的,那么构造函数也必须是私有的吗?
不,没有这样的限制。 见JLS§8.8.3。 构造函数修饰符 。
值得指出的是,只有嵌套类可以声明为private
。 JLS允许此类的构造函数使用任何有效的访问修饰符。
如果你的意思是嵌套类, 答案是否定的 。 使内部类私有使它只能在外部类中使用。
编辑:外部类似乎可以完全访问内部类的内部,而不管它们的访问修饰符。 这使我的上述推理无效,但无论如何,都没有这样的限制。 奇怪的是,现在似乎如果内部类是private
,它的构造函数本质上是 private
,无论其访问修饰符如何,因为没有其他人可以调用它。
不,没有。 相反,如果使用私有构造函数(私有类的默认值)从外部类创建内部类的实例,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
不,它没有修复,你可以设置私人/公共/任何你想要的。
但在某些情况下,当您不希望允许其他类创建此类的对象时,我更喜欢将构造函数设为私有。 那么在这种情况下你可以通过设置构造函数private来做这样的事情。
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;
}
}
顺便说一下,这取决于您的要求。
它不必是私有的。 但它可以。 例:
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();
}
如果在私有内部类上使用private
或public
构造函数,则没有任何区别。 原因是内部类实例是外部类实例的一部分。 这张照片说明了一切:
请注意,我们正在谈论一个内部阶级 。 如果嵌套类是static
,那么官方术语是静态嵌套类 ,它与内部类不同。 只需调用new Outer.Inner()
就可以在没有外部类实例的情况下访问公共静态嵌套类。 有关内部类和嵌套类的更多信息,请参见此处。 http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.