内部类&异常处理&File类笔记
内部类
概念:定义在一个类中的类
public class Student{
String name;
int score;
Birth birth;
//定义内部类
class Birth{
int year;
int month;
int day;
}
}
思考:什么情况下创建内部类?
当类Birth只提供给类Student使用时,考虑将类Birth定义为类Student的内部类
如何使用内部类创建对象
代码
public class Student{
private String name;
private int score;
private Birth birth;
public Student(String name, int score, int year, int month, int day){
this.name = name;
this.score = score;
//创建内部类对象
this.birth = new Birth(year, month, day);
}
class Birth{
int year;
int month;
int day;
public Birth(){
this.year = year;
this.month = month;
this.day = day;
}
}
}
思考:内部类Birth中可以访问Student中的私有成员吗?
可以。内部类相当于Student中的一个成员,当然可以访问Student中的所有成员。
内部类的访问权限可以为 private, 默认不写, protected, public
匿名内部类对象
概念:由一个没有名字的内部类生成的对象。
思考:没有名字的内部类如何定义?没有名字的类如何创建对象?
定义类和创建对象在必须在一起
public class A{
int a;
public void fun(){
System.out.println(a);
}
}
public class B{
int b;
A a;
public B(int b, A a){
this.b = b;
//匿名内部类对象
this.a = new A(){
public void fun(){
super.fun();
System.out.println("sub a");
}
};
}
}
通过内部类生成的对象只有一个时,考虑使用匿名内部类对象。
异常机制
异常概念:由于编程错误或者偶然的外界因素,导致在程序运行过程中所发生的异常事件。
异常会中断指令,程序被强制退出。
异常分类:
运行时异常
由于编程错误导致 (强烈建议程序员修改bug)
NullPointerException 空指针异常
ArrayIndexOutOfBoundsException 数组越界异常
NumberFormatException 数字格式化异常
NegativeArraySizeException 数组长度异常
ClassCastException 类型转换异常
非运行时异常
由于外界因素导致 (建议捕获异常,防止程序崩溃退出)
文件找不到异常 FileNotFoundException
异常捕获机制
try{
//可能抛出异常的语句
}catch(Exception){
//捕获异常,输出异常信息
}finally{
//无论有没有抛出异常,都会执行,通常用来清理资源,例如关闭socket,关闭流,关闭数据库连接等等
}
注意
如果try中的语句抛出异常,立即执行catch中的语句捕获异常。
使用多重catch语句时,异常子类一定要位于异常父类之前
throw 抛出异常对象
throws 可能抛出的异常类型
File对象
概念
java.io.File类用于表示文件(目录)
File类只用于表示文件(目录)的信息(名称、大小等),不能用于文件的读写
常用方法
//创建方法
boolean createNewFile() //不存在返回true 存在返回false
boolean mkdir() //创建目录
boolean mkdirs() //创建多级目录
//删除方法
//boolean delete()
//判断方法
boolean exists() //判断文件是否存在
boolean isFile() //判断是否为文件
//获取方法
String getName()
String getPath()
String getParent() //如果没有父目录返回null
long lastModified() //获取最后一次修改的时间
long length() //获取文件大小
File[] listFiles() //列出全部文件
利用递归列出全部文件
public class FileDemo5 {
public static void main(String[] args){
File f = new File("E:/音乐");
showDir(f);
}
public static void showDir(File dir){
System.out.println(dir);
File[] files = dir.listFiles();
for(File file:files){
if(file.isDirectory())
showDir(file);
else
System.out.println(file);
}
}
}