内部类的访问规则
1.内部类可以直接访问外部类中的成员,包括私有
格式:外部类名.this
2.外部类要访问内部类,必须要建立内部类对象
访问格式
Outer.inner in =new outer().new inner();
3.当内部类在成员位置上,就可以被成员修饰符所修饰
当内部类被static修饰后,只能访问外部类中的static成员,出现了访问局限。
在外部其他类中,如何直接访问static内部类的非静态成员呢
new outer.inner().function();
注意:当内部类中定义了静态成员,该内部类必须是static的
当描述事物时,事物的内部还有事物,该事物用内部类来描述
异常
严重的:Error类,一般不变着针对性代码进行处理
非严重的:Exception类,可以使用针对性的处理方式进行处理
Throwable是所有错误和异常的父类
异常的处理
try
{
需要被检测的代码
}
catch(异常类 变量)
{
处理异常的代码(处理方式)
}
finally
{
一定会执行的语句
}
对捕获到的异常对象进行常见方法操作
String getMessage():获取异常信息
多异常的处理
1.声明异常时,建议声明更为具体的异常,这样处理更具体。
throws …
2.对方声明几个异常,就对应有几个catch块
如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面
自定义异常
自定义异常类
当在函数内部出现了throw抛出异常对象,那么就必须要给出对应的处理动作,要么在内部try catch处理,要么在函数上声明让调用者处理。
定义异常信息:因为父类中已经吧异常信息的操作都完成了,所以子类只要在构造时,将异常信息都通过super语句传递给父类,就可以直接通过getMessage方法获取自定义的异常
class negativeException extends Exception
{
negativeException(String msg)
{
super(msg);
}
}
手动通过throw关键字抛出一个自定义异常对象
throw new negativeException
throw和throws的区别
throws使用在函数上,后面跟的异常类可以有多个,用逗号隔开
throw后面跟的是异常对象,使用在函数内
RuntimeException运行时异常
在函数内抛出该异常,函数上可以不用声明,编译一样通过
如果在函数上声明了该异常,调用者可以不用进行处理,编译一样通过
对于异常分为两种
1.编译时被检测的异常
2.编译时不被检测的异常(运行时异常,runtimeException以及其子类)
异常练习代码
class bluescreenException extends Exception
{
bluescreenException(String message)
{
super(message);
}
}
class smokeException extends Exception
{
smokeException(String message)
{
super(message);
}
}
class noplanException extends Exception
{
noplanException(String msg)
{
super(msg);
}
}
class computer
{
private int state=3;
public void run()throws bluescreenException,smokeException
{
if(state==2)
throw new bluescreenException("蓝屏");
if(state==3)
throw new smokeException("冒烟");
System.out.println("run");
}
public void reset()
{
state = 1;
System.out.println("电脑重启");
}
}
class teacher
{
private String name;
private computer cmpt;
teacher(String name)
{
this.name=name;
cmpt=new computer();
}
public void prelect()throws noplanException
{
try
{
cmpt.run();
}
catch(bluescreenException e)
{
cmpt.reset();
}
catch(smokeException e)
{
test();
throw new noplanException("课时无法继续"+e.getMessage());
}
System.out.println("teacher");
}
public void test()
{
System.out.println("练");
}
}
class exceptiontest
{
public static void main(String[] args)
{
teacher t=new teacher("bei");
try
{
t.prelect();
}
catch (noplanException e) {
System.out.println(e.toString());
System.out.println("换老师");
}
}
}