java中內(nèi)部類中還有內(nèi)部類請給實例
當(dāng)內(nèi)部類中還有一個內(nèi)部類,下面給出了一個實例?!拘率挚珊雎圆挥绊懤^續(xù)學(xué)習(xí)】(以下多出代碼, 用藍(lán)色標(biāo)記)
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
例2.2:---本章源碼
class ShellMark_to_win {
int shell_x = 100;//馬克-to-win:既然每個內(nèi)部類實例都可以改變這里的外層類靜態(tài)屬性或?qū)嵗龑傩?,這里成為內(nèi)部類實例們可以交互的地方
static int n;
void visitCore() {
Core core = new Core();
core.y=8;
core.display();
}
// 下面是個實例內(nèi)部類,必須有個外層類實例,才能有這個內(nèi)部類實例。所以就有了this這個概念。
class Core {
/* 下一句錯誤,根據(jù)語法:馬克-to-win:靜態(tài)的域或方法只能出現(xiàn)在靜態(tài)類或最外層類上。The field m cannot be declared static; static fields can only be declared in static inner class or top level classes,*/
// static int m=9;
int y = 10; // y is local to core
void display() {
shell_x=shell_x+20;
n=n+1;//輕松訪問外層類的靜態(tài)變量
System.out.println("n is "+n+" display: shell_x and y " + shell_x + " "+ShellMark_to_win.this.shell_x+ " " + y+ " "+this.y);
}
class CoreCore{
void displayDis() {
Core.this.display();
}
}
}
Core newC()
{
return new Core();
}
void showy() {
// y=9; // 錯誤,馬克-to-win:外層類不能直接訪問內(nèi)部類的屬性。error,y not known here! System.out.println(y);
}
}
public class Test {
public static void main(String args[]) {
ShellMark_to_win shell = new ShellMark_to_win();
shell.visitCore();
ShellMark_to_win.Core sc=shell.new Core();//馬克-to-win:內(nèi)部類是存在于外部對象里的。
sc.display();
ShellMark_to_win.Core.CoreCore scc=sc.new CoreCore();
scc.displayDis();
ShellMark_to_win.Core sc1=shell.newC();
sc1.display();
/* 不能像下面這樣寫, 因為Core 是內(nèi)部類。 can not resolve Core class ,because Core class are defiened as ShellMark_to_win's inner class. */
//Core core = new Core();
}
}
result is:
n is 1 display: shell_x and y 120 120 8 8
n is 2 display: shell_x and y 140 140 10 10
n is 3 display: shell_x and y 160 160 10 10
n is 4 display: shell_x and y 180 180 10 10