私人类的构造函数是否必须是私有的?
不,没有这样的限制。见JLS §8.8.3. Constructor Modifiers。
值得指出的是,只有一个嵌套类可以被声明为private
。 JLS允许这样的类的构造函数使用任何有效的访问修饰符。
如果你的意思是嵌套类,答案是不是。使内部类为私人使它只能在外部类中使用。
编辑:看来外层类可以完全访问内部类的内部,而不管它们的访问修饰符如何。这使我的上述推理无效,但无论如何,没有这种限制。奇怪的是,现在看来,如果内部类是private
,它的构造函数是本质上是private
,无论它的访问修饰符如何,因为没人能调用它。
你确定吗?我做了几个实验,并且我可以从外部类创建一个内部类的实例,即使内部类的构造函数是'private' *。 – NPE 2013-03-13 09:22:09
@NPE我打算基于逻辑,但看起来你是对的,它在[为什么外部Java类可以访问内部类私有成员?](http://*.com/q/1801718)接受的答案不幸倒退.. – 2013-03-13 09:28:37
Java中的一个通用规则是,所有'private'成员都可以在它们出现的最外面的词汇范围内访问。 – 2013-03-13 09:29:44
不,它没有修复,你可以将它设置为私人/公共/任何你想要的。
但是在某些情况下,如果您不想让其他类创建此类的对象,我宁愿将构造函数设为私有。那么在这种情况下,您可以通过将构造函数设置为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
不,它没有。相反,如果使用外部类的私有构造函数(这是默认的私有类)创建内部类的实例,Java将创建一个额外的类来防止访问冲突并保持JVM的快乐
如果你编译此类
class Test {
private class Test2 {
Test2() {
}
}
Test() {
new Test2();
}
}
javac将创建Test.class,Test @ Test2。类
,如果你编译这个类
class Test {
private class Test2 {
}
Test() {
new Test2();
}
}
的javac将创建的Test.class,[email protected],测试$ 1.class
知道最好的办法是你自己尝试一下,看看.. :)顺便说一句,*类的不能是私人只有内部类的罐头。 :) – PermGenError 2013-03-13 09:15:17
考虑一个私有类中的非私有构造函数,如何从另一个类访问它? – 2013-03-13 09:16:10
答案是**不是** – pktangyue 2013-03-13 09:16:42