?? 109606881c75001d1dddb6604daa6ad2
字號:
//【例4-23】 靜態局部類和實例局部類的定義、訪問控制、約束與引用。
//程序清單4-23: StaticIntanceLocalClass.java
package e4_23;
public class StaticIntanceLocalClass {
public static void main(String[] args) {
Outer outer = new Outer();
outer.intanceMethod();// 實例名.實例方法()
Outer.staticMethod();// 類名.靜態方法()
// 局部類所在代碼塊或方法體以外的地方不可見
// new Outer().new Inner1();
}
}
class Outer {
private int x;
private static int y;
// 在外部類的實例代碼塊中定義實例局部類
{// 實例初始化代碼塊
int lx = 0;
final int ly = 1;
class Inner1 {// 實例局部類
public void InnerM1() {
x = 1;// 實例局部類能直接訪問外部類的成員變量
Outer.this.y = 10;// 可用"OuterClass.this"獲得外部類的實例
// 在實例局部類所在代碼塊中,不能訪問非final類型的局部變量
// System.out.print(lx);
// 在實例局部類所在代碼塊中,能訪問final類型的局部變量
System.out.println("在實例局部" + this.getClass()
+ "中訪問其代碼塊中的final int ly = " + ly);
System.out.println("在實例局部" + this.getClass()
+ "中訪問Outer類中的private static int y = " + y);
System.out.println("在實例局部" + this.getClass()
+ "中訪問Outer類中的private int x = " + x);
}
}
// 只能在方法體或代碼塊中創建局部類例,且創建的實例也只能在局部域中被訪問。
new Inner1().InnerM1();
// 局部類不能加訪問控制修飾符public、protected、private
// public class inner2 { }
}
// 在外部類的靜態代碼塊中定義靜態局部類
static {// 靜態初始化代碼塊
class Inner2 {// 靜態局部類
public Inner2() {
// 靜態局部類只能訪問外部類的靜態變量和靜態方法
y = 100;
staticMethod();
// 靜態局部類不能訪問外部類的實例變量和實例方法,
// x = 2;
// intanceMethod();
System.out.println("在靜態局部" + this.getClass()
+ "中訪問Outer類中的private static int y = " + y);
}
}
// 只能在方法體或代碼塊中創建局部類例,且創建的實例也只能在局部域中被訪問。
new Inner2();
}
public void intanceMethod() {// 在外部類的實例方法中定義實例局部類
class Inner4 {// 實例局部類的嵌套定義
// new Inner3();
}
class Inner3 {
class Inner4 {// 實例局部類的嵌套定義
public Inner4() {
System.out.println("在嵌套實例局部" + this.getClass()
+ "中訪問Outer類中的private static int y = " + y);
}
}
}
// 局部類只在其所在代碼塊域或方法域中可見
// Outer.Inner2 inner2;
new Inner3().new Inner4();
}
static void staticMethod() {
class Inner4 {// 在外部類的靜態方法中定義靜態局部類
public Inner4() {
y = 200;// 靜態局部類只能訪問外部類的靜態變量和靜態方法
System.out.println("在靜態局部" + this.getClass()
+ "中訪問Outer類中的private static int y = " + y);
// 靜態局部類不能訪問外部類的實例變量和實例方法,
// x = 2;
// intanceMethod();
}
}
new Inner4();
// 接口不能定義成局部類
// interface I { }
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -