1 成員內部類
public class test{
public String msg = "aaa";
class A{
public void say(){
String msg = "";
System.out.println(test.this.msg);
System.out.println(this.msg);
}
}
}
1.1 編譯生成class test.class,A$.class
1.2 使用環境
1.2.1 只有test調用,其他地方不需要使用
1.2.2 兩個類之間數據共享(例如:類A中可以直接使用msg)
1.2.3 局部變量需要有默認值,成員變量可以沒有默認值
1.2.4 不能實例化 A a = new A();靜態方法中不能使用 this, new 相當於 this.new 但是不能這麼寫
1.2.5 實例化方法 test t = new test(); A a = t.new A();
1.2.6 this 代表當前類對象 test.msg this.msg
1.3 使用情況 少量使用
2 靜態內部類
public class test{
public static class B{
private static int age;
private String msg;
}
}
2.1 編譯生成class test.class B$.class2.2 使用環境
2.2.1 沒有對象也可以訪問到
2.2.2 靜態內部類可以直接實例化 B b = new B();
2.3 類加載時由類加載器 分配靜態塊,靜態代碼區專門放置
2.4 使用情況 基本不使用
3 局部內部類
public class test{
//方法內部類,內部調用
public void say(){
class C{
private int age;
private String msg;
public void say(){
System.out.println(age);
}
}
C c = new C();
c.say();
}
}
3.1 編譯生成class test.class C1$.class3.2 使用環境
3.2.1 只有內部方法使用
3.2.2 內部直接實例化,使用C c = new C();
3.3 使用情況 基本不使用
4 匿名內部類
public class test{
private int[] arr;
public void test(int[] arr){
this.arr = arr;
}
public void sort(int[] arr){
Arrays.sort(arr);
}
public void display(action a){
System.out.println("before:"+Arrays.toString(arr));
//Arrays.sort(arr);
//sort(arr);
a.sort();
System.out.println("after:"+Arrays.toString(arr))
}
public static void main(){
int[] arr = {1,42,2,3};
test t = new test(arr);
//接口匿名內部類
action a = new action(){
public void sort(int[] arr){
Arrays.sort(arr);
}
};
t.display(a);
//或者
t.display(new action(){
public void sort(int[] arr){
Arrays.sort(arr);
}
})
}
}
interface action{
public void sort(int[] arr);
}
4.2 使用環境4.2.1 匿名內部類:必須繼承一個父類或實現一個接口
4.2.2 匿名內部類只能使用一次
4.2.3 使用匿名內部類可以根據情況靈活改變代碼,
就比如上個例子,直接排序,和調用方法排序,只能實現一種排序方法
如果你還想根據其他因素排序,就無法實現,就還需要在寫一個方法調用
4.3 使用情況 使用頻繁