一、内部类
1、定义
定义: 定义在一个类型当中的类被称作内部类
作用: 共享数据 & 表达类和类之间的专属关系
2、四种内部类的类型
成员内部类: 外部类所有[静态+非静态]成员[属性+方法]
Outer.Inner in = new Outer().new Inner();
静态内部类: 外部类静态成员[属性+方法]
Outer.Inner in = new Outer.Inner();
局部内部类:
定义在静态方法中:只能共享外部类静态成员
定义在非静态方法中:能够共享外部类所有成员
由于ta出现在外部类的方法体当中
还能共享其所在的外部类方法中的局部变量
只是JDK8.0之前 必须加final 8.0开始默认final
Inner in = new Inner();
注意有位置限定:定义完成之后 所在方法结束之前
匿名内部类: 可能等价于上述三种的某一种 取决于定义的位置
new 父类/接口(){
完成抽象方法的具体实现
}
3、Java中共享数据的三种方式
(1)静态数据 (2)传参 (3)内部类
二、异常
1、error与Exception的区别
Error : 由于 [硬件环境][系统原因],产生的较严重的问题
Exception: 程序在运行时产生的例外情况而已
2、异常处理
1>throws 抛还给上一级
2>try catch finally 自行处理//catch可以(异常类型1 | 异常类型2 e){ }
finally中不应该出现return语句,否则后面的代码就没有意义了。
3、运行时异常和异常的区别
运行时异常,在编译的时候不需要给出处理方案,编译能够直接通过,问题会在运行时直接体现出来
它们都继承RuntimeException
非运行时异常,在编译的时候必须给出处理方案,否则编译无法通过
直接继承Exception
4、13种异常
1(运算符)+2(数组)+3(字符串)+1(类型转换)+4(集合)+2(线程)
1: 运算符
ArithmeticException = 算术异常
2: 数组
NegativeArraySizeException = 负数数组大小异常
ArrayIndexOutOfBoundsException = 数组索引值超出边界异常
3: 字符串
NullPointerException = 空指针异常
StringIndexOutOfBoundsException = 字符串索引值超出边界异常 substring() indexOf()
NumberFormatException = 数字格式异常
1: 类型转换
ClassCastException = 类型造型异常
4: 集合
IllegalArgumentException = 非法参数异常
IndexOutOfBoundsException = 索引值超出边界异常
IllegalStateException = 非法状态异常
ConcurrentModificationException = 并发修改异常
//IllegalStateException => 非法状态异常
List<Integer> list3 = new ArrayList<>();
Collections.addAll(list3,11,22,33);
Iterator<Integer> car = list3.iterator();
car.remove();
//IndexOutOfBoundsException => 索引值超出边界异常
List<Integer> list2 = new ArrayList<>();
Collections.addAll(list2,11,22,33);
System.out.println(list2.get(3));
//IllegalArgumentException => 非法参数异常
List<Integer> list1 = new ArrayList<>(-7);
//ClassCastException => 类造型异常
Object stu = new Student();
Cacti cc = (Cacti)stu;
//NumberFormatException => 数字格式异常
String str3 = "12a3";
int price = Integer.parseInt(str3);
System.out.println(price+2);
//StringIndexOutOfBoundsException => 字符串索引值超出边界异常
String str2 = new String("ETOAK");
System.out.println(str2.charAt(5));//substring()
//NullPointerException => 空指针异常
String str1 = null;
System.out.println(str1.length());
//ArrayIndexOutOfBoundsException => 数组索引值超出边界异常
int[] data2 = new int[]{11,22,33};
System.out.println(data2[3]);
//NegativeArraySizeException => 负数数组大小异常
int[] data1 = new int[-3];
//ArithmeticException => 算术异常
System.out.println(5 / 0);
2:线程
IllegalThreadStateException = 非法线程状态异常
IllegalMonitorStateException = 非法锁标记状态异常
5、throw和throws的区别
throw出现在方法体当中 在本没有异常的情况下
主动制造异常出现的场景
throws用在方法签名的最后 用于表达
本方法当中出现指定种类的异常 方法当中不做处理
抛还给调用的上级进行处理
6、自定义异常
自己定义一个类 选择继承Exception / RuntimeException
在其构造方法的首行使用super("指定描述信息");