1. 程式人生 > >非靜態內部類為什麼可以訪問外部類的靜態成員

非靜態內部類為什麼可以訪問外部類的靜態成員

非靜態內部類物件寄生於外部類物件,inn呼叫test()方法時,知道自己呼叫的是它寄生的物件所屬類的類成員;

在階段一:類載入的時候沒有建立外部類物件,但是方法是知道要呼叫的是外部類的類成員,已經確定了

在第二階段:建立非靜態內部類物件,該物件必須寄生於外部類物件,它知道要呼叫自己寄生的這個物件所屬的類的類方法,也是確定的

public class TestOutInn {


public static void main(String[] args) {
OutA out=new OutA();
OutA.InnA inn=out.new InnA();//inn 寄生於out,沒有out一定沒有inn
inn.test();//方法是用來被呼叫的,當inn呼叫test方法時,它知道f(),a都屬於誰,所以底層跑的時候很清楚
OutA.InnB innb=new OutA.InnB();//從建立內部類的方式就可以看出innb是屬於類的
innb.show();//底層不知道是哪個物件的weight值,會報異常
}


}
class OutA{
int weight;
private static int a=8;
private static void f(){
System.out.println("外部類靜態方法");
}
class InnA{

public void test(){

/**
* 如果內部類的變數名和外部類的變數名相同,要注意區分

*/
int a=10000;
System.out.println(a);//預設是this的a
System.out.println(OutA.a);//在這裡要寫成(OutA.a)
System.out.println(this.a);//在這裡呼叫的是非靜態內部類物件的a
f();
}
}
static class InnB{
public void show(){
System.out.println(weight);
}
}
}
/*
 * 在java中執行的結果是:
 * 10000
 * 8
 * 10000
 * 外部類靜態方法
 * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 * Cannot make a static reference to the non-static field weight
 *
 * at cn.zhishidian.ying.OutA$InnB.show(TestOutInn.java:29)
 * at cn.zhishidian.ying.TestOutInn.main(TestOutInn.java:10)

*/