考虑以下程序:
public class A
{
public static void main(String[] args)
{
class B
{
private B()
{
System.out.println("local");
}
}
// how are we able to create the object of the class having private constructor
// of this class.
B b1= new B();
System.out.println("main");
}
}
输出:本地main
具有私有构造函数的类意味着我们只能在类内创建对象,但在这里我们可以在类外创建实例。有人能解释一下我们如何在B类之外创建B的对象吗?
发布于 2013-06-16 12:00:10
发布于 2013-06-16 11:59:59
您甚至还可以访问该类的私有变量(试试吧!)。
这是因为您在调用该类的同一个类中定义了该类,因此您对该类有私有/内部的了解。
如果将B类移出A类,它将按预期工作。
发布于 2013-06-16 12:02:45
请参阅JLS 6.6.1
否则,如果成员或构造函数被声明为私有,则当且仅当它出现在包含成员或构造函数声明的顶级类(§7.6)的主体内时,才允许访问。
实现这一点的方法是使用合成的包保护方法。
“如果您希望隐藏内部类的私有成员,则可以定义一个具有公共成员的接口,并创建实现此接口的匿名内部类。请参阅代码:”
class ABC{
private interface MyInterface{
public void printInt();
}
private static MyInterface mMember = new MyInterface(){
private int x=10;
public void printInt(){
System.out.println(String.valueOf(x));
}
};
public static void main(String... args){
System.out.println("Hello :: "+mMember.x); ///not allowed
mMember.printInt(); // allowed
}
}
https://stackoverflow.com/questions/17133003
复制相似问题