为什么外部Java类可以访问内部类私有成员?我注意到,外部类可以访问内部类、私有实例变量。这怎麽可能?下面是演示相同的示例代码:class ABC{
class XYZ{
private int x=10;
}
public static void main(String... args){
ABC.XYZ xx = new ABC().new XYZ();
System.out.println("Hello :: "+xx.x); ///Why is this allowed??
}}为什么允许这种行为?
3 回答
婷婷同学_
TA贡献1844条经验 获得超8个赞
如果在单独的类中实现的话,外层类中的某些功能将是最明确的。 尽管它位于一个单独的类中,但它的功能与外部类的工作方式密切相关。
HUX布斯
TA贡献1876条经验 获得超6个赞
class ABC{
private interface MyInterface{
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
}}添加回答
举报
0/150
提交
取消
