什麼是實例內部類 Instance inner class有什麼語法? ...
1.Instance inner class定義,用途和用法 (視頻下載) (全部書籍)
重要語法:馬克-to-win:1)實例內部類一定得有個外層類的實例和它綁定在一起,所以可以用This指針。所以必須先實例化外層類之後才能再實例化內部類。(生活中的例子就是子宮和胚胎(不算試管嬰兒!))2)語法規定:實例內部類不能有靜態的屬性或方法,為什麼?因為沒有外層類的實例就不應該有實例內部類的任何東西存在,包括內部類的靜態屬性,但靜態屬性應該在main方法執行時創建,這樣就會產生矛盾,所以規定實例內部類不能有靜態的屬性或方法。馬克-to-win:2)既然每個內部類實例都可以改變他們共同的外層類的靜態屬性或實例屬性,他們成為內部類實例們可以交互的地方。(下例中的shell_x,在不斷增長。)
例2.1a:類中有個內部類屬性。
class ShellMark_to_win {
int shell_x = 100;//既然每個內部類實例都可以改變這裡的外層類靜態屬性或實例屬性,馬克-to-win:這裡成為內部類實例們可以交互的地方
static int n;
Core core;
void visitCore() {
core = new Core();
core.y=8;
core.display();
}
// 下麵是個實例內部類,必須有個外層類實例,才能有這個內部類實例。所以就有了this這個概念。
class Core {
/* 下一句錯誤,根據語法:馬克-to-win:靜態的域或方法只能出現在靜態類或最外層類上。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;//輕鬆訪問外層類的靜態變數
System.out.println("n is "+n+" display: shell_x and y " +
shell_x + " "+ShellMark_to_win.this.shell_x+ " " + y+ " "+this.y);
}
}
Core newC()
{
return new Core();
}
void showy() {
// y=9; // 錯誤,馬克-to-win:外層類不能直接訪問內部類的屬性。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();//內部類實例是存在於外部對象里的。
sc.display();
ShellMark_to_win.Core sc1=shell.newC();
。。。。。。。。。。。。。。。。。
詳情請進:http://www.mark-to-win.com/index.html?content=JavaBeginner/javaUrl.html&chapter=JavaBeginner/JavaBeginner4_web.html#WhatIsInstance