内部类

来源:互联网 发布:root软件哪个成功率高 编辑:程序博客网 时间:2024/05/21 11:20

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$.class
        2.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$.class
        3.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 使用情况 使用频繁

      

1 0
原创粉丝点击