我可以理解为什么内部类可以访问外部类私有成员,但是不清楚为什么外部类方法中定义的内部类的实例可以访问内部类私有成员。例如:以下代码可以正常工作。
class OuterClass
{
int outer_default;
private int outer_private;
protected int outer_protected;
static int outer_static;
static {
outer_static=5;
}
public OuterClass()
{
outer_default=1;
outer_private=2;
outer_protected=3;
System.out.println("Outerclass object created!!!!");
}
public void outerMethod()
{
System.out.println("**********Outerclass accessing outer class members********************");
System.out.println("outerdefault: "+outer_default);
System.out.println("outerprivate: "+outer_private);
System.out.println("outerprotected: "+outer_protected);
System.out.println("outerstatic: "+outer_static);
System.out.println("**************************************************************");
InnerClass innerObj = new InnerClass();
System.out.println("**********Outerclass accessing inner class members********************");
System.out.println("innerdefault: "+innerObj.inner_default);
System.out.println("innerprivate: "+innerObj.inner_private); //HOW IS THIS POSSIBLE??????
System.out.println("innerprotected: "+innerObj.inner_protected);
System.out.println("**************************************************************");
}
class InnerClass
{
int inner_default;
private int inner_private;
protected int inner_protected;
public InnerClass()
{
inner_default=4;
inner_private=5;
inner_protected=3;
System.out.println("Innerclass object created!!!!");
}
public void innerMethod()
{
System.out.println("**********Innerclass accessing inner class members********************");
System.out.println("innerdefault: "+inner_default);
System.out.println("innerprivate: "+inner_private);
System.out.println("innerprotected: "+inner_protected);
System.out.println("**************************************************************");
System.out.println("**********Innerclass accessing outer class members********************");
System.out.println("outerdefault: "+outer_default);
System.out.println("outerprivate: "+outer_private);
System.out.println("outerprotected: "+outer_protected);
System.out.println("outerstatic: "+outer_static);
System.out.println("**************************************************************");
}
}
}
class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.outerMethod();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.innerMethod();
}
}
我已经在我怀疑的代码附近发表了评论。