packagecom.oop;publicclassP76_Test{publicstaticvoidmain(String[] args){Apple apple =newApple();// 匿名内部类,没有名字初始化类,不用将实例保存到变量中newApple().eat();// 匿名内部类UserService userService =newUserService(){@Overridepublicvoidhello(){}};}}classApple{publicvoideat(){System.out.println("1");}}interfaceUserService{voidhello();}
packagecom.oop;publicclassP76_Outer{privateint id =10;publicvoidout(){System.out.println("这是外部类的方法");}classInner{publicvoidin(){System.out.println("这是内部类的方法");}// 获得外部类的私有属性publicvoidgetID(){System.out.println(id);}}}
packagecom.oop;publicclassP76_Outer{privateint id =10;publicvoidout(){System.out.println("这是外部类的方法");}classInner{publicvoidin(){System.out.println("这是内部类的方法");}// 获得外部类的私有属性publicvoidgetID(){System.out.println(id);}}}
4P77 Error和Exception
packagecom.exception;// 检查性异常、运行时异常 和 错误publicclass P77 {publicstaticvoidmain(String[] args){// new P77().a();// System.out.println(11/0);}// public void a(){// b();// }// public void b(){// a();// }}
4P78 捕获和抛出异常
packagecom.exception;publicclass P78 {publicstaticvoidmain(String[] args){// int a = 1;// int b = 0;newP78().test(1,0);}// public void a(){// b();// }// public void b(){// a();// }// 假设这方法中,处理不了这个异常。方法上可抛出异常publicvoidtest(int a,int b)throwsArithmeticException{if(b ==0){//主动抛出异常thrownewArithmeticException();//主动抛出异常,一般在方法中使用}// System.out.println(a/b);}} 假设要捕获多个异常:从小到大 finally可以不写 IO资源需要关闭就需要finally// try { //try监控区域// new P78().a();// }catch (Error e){ //处理异常(想要捕获的异常类型)// System.out.println("有异常,变量b不能为0");// }catch (Exception e){// System.out.println("Exception");// }catch (Throwable t){// System.out.println("Throwable");// }//// finally { // 处理善后工作// System.out.println("finally");// }
packagecom.exception;publicclass P78_1 {publicstaticvoidmain(String[] args){int a =1;int b =0;// Ctrl + alt + Ttry{System.out.println(a/b);}catch(Exception e){System.exit(1);
e.printStackTrace();//打印错误栈信息}finally{}}}