内部类

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 使用情况 使用频繁

      

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值