Java基础--面向对象(内部类、异常)

来源:互联网 发布:网络教育机构排名 编辑:程序博客网 时间:2024/05/19 18:47

内部类

内部类访问规则

  1. 概述:将一个类定义在另一个类的里面,对里面那个类就称为内部类(内置类、嵌套类)
  2. 访问特点:
    • 内部类可以直接访问外部类中的成员,包括私有成员;
    • 而外部类要访问内部类中的成员必须要建立内部类的对象;
  3. 直接访问内部类中的成员:
    格式:Outer.Inner in=new Outer().new Inner();
       in.function();//内部类功能;  
       知识点扩展:调用某个类中的方法要先建立该方法所属类 的对象,而后才能调用该类中的方法即属性;静态方法可直接通过“类名.方法名”的方式调用;
      注意:当外部类,内部类,局部都有同名变量时,访问变量的方式如下(设该变量为x):
    x:访问局部变量x;
    this.x:访问内部类变量x;
    Out.this.x:访问外部类中的同名变量x;

示例代码:

class Outer{    private int x = 3;    class Inner{//内部类        //int x = 4;        void function(){            //int x = 6;            System.out.println("innner :"+Outer.this.x);        }    }    void method(){        Inner in = new Inner();        in.function();    }}class  InnerClassDemo{    public static void main(String[] args) {        Outer out = new Outer();        out.method();        //直接访问内部类中的成员。//      Outer.Inner in = new Outer().new Inner();//      in.function();    }}

静态内部类

  1. 当内部类在成员位置上,就可以被成员修饰符修饰;
    比如:private,static
    当内部类被static修饰后,只能直接访问外部类中的static成员,出现访问局限性;
  2. 在外部其他类中直接访问static内部类:
    new Outer.Inner().function();
  3. 在外部其他类中,直接访问static内部类静态成员:
    Outer.Inner.function();
    注意:
    • 当内部类中定义了静态成员,该内部类必修是static的;
    • 当外部类中的静态方法访问内部类时,内部类也必须是static的;

示例代码:

class Outer{    private static  int x = 3;    static class Inner{//静态内部类        static void function(){            System.out.println("innner :"+x);        }    }    static class Inner2{        void show(){            System.out.println("inner2 show");        }    }    public static void method(){        //Inner.function();        new Inner2().show();    }}class  InnerClassDemo2{    public static void main(String[] args) {        Outer.method();        //Outer.Inner.function();        //new Outer.Inner().function();        //直接访问内部类中的成员。//      Outer.Inner in = new Outer().new Inner();//      in.function();    }}

何时定义内部类

  当描述事物时,事物的内部还有事物,该事物用内部类描述,因为内部类事物在使用外部类事物的内容。
注:
1. 一般内部类定义在成员位置上时才能被private和static所修饰,一般内部类不会被公有修饰,但有特殊情况:接口;
2. 内部类可以写在类的任意位置上:成员或局部(此时不可以被private即static修饰,因为此两个修饰符只能修饰成员)。

内部类定义在局部时:

  1. 不可以被成员修饰符修饰,例:static;
    内部类在局部时,内部类中的方法,需要建立内部类对象才可以被调用;
  2. 可以直接访问外部类中的成员,因为还持有外部类中的引用,但是不可以访问他所在的局部中的变量,只能访问被final修饰的局部变量;

示例代码:

class Outer{    int x = 3;    void method(final int a){        final int y = 4;        class Inner{            void function(){                System.out.println(y);            }        }        new Inner().function();    }}class  InnerClassDemo3{    public static void main(String[] args) {        Outer out = new Outer();        out.method(7);        out.method(8);    }}

匿名内部类

  1. 匿名内部类其实就是内部类的简写格式;
  2. 定义匿名内部类的前提:内部类必须是继承了一个类或者实现接口;
  3. 匿名内部类的格式:new 父类或者接口(){定义子类的内容}
  4. 其实匿名内部类就是一个匿名子类对象,而且这个对象有点胖,可以理解为带内容的对象(例:抽象类不可以创建对象,但是创建抽象类对象并带内容时,就是匿名内部类);
  5. 匿名内部类中定义的方法最好不要超过3个,通常在使用方法是接口类型参数时,可以将匿名内部类作为参数传递,增强阅读性;

示例代码:

abstract class AbsDemo{    abstract void show();}class Outer{    int x = 3;    /*    class Inner extends AbsDemo{        int num = 90;        void show(){            System.out.println("show :"+num);        }        void abc(){            System.out.println("hehe");        }    }    */    public void function(){        //AbsDemo a = new Inner();//      Inner in = new Inner();//      in.show();//      in.abc();        AbsDemo d = new AbsDemo(){            int num = 9;            void show() {                System.out.println("num==="+num);            }            void abc(){                System.out.println("haha");            }        };        d.show();        //d.abc();//编译失败;    }}class InnerClassDemo4 {    public static void main(String[] args)  {        new Outer().function();    }}

异常

概述:就是程序在运行时出现的不正常情况;

异常体系 Throwable(抛出)

  1. Error:
    • 通常出现重大问题,如:运行的类不存在或者内存溢出等;
    • 不编写针对代码对其处理
  2. Exception
    • 在运行时运行出现的一起情况,可以通过try catch finally解决异常;
    • RuntimeException:特殊异常,抛该异常可不用声明不处理,程序停止运行;
  3. Exception和Error的子类名都是以父类名作为后缀;

示例代码:

class Demo{    int div(int a,int b)throws Exception{//在功能上通过throws的关键字声明了该功能有可能会出现问题。        return a/b;    }}class  ExceptionDemo{    public static void main(String[] args) {        Demo d = new Demo();        try{            int x = d.div(4,1);            System.out.println("x="+x);        }catch (Exception e){//Exception e = new ArithmeticException();            System.out.println("除零啦");            System.out.println(e.getMessage());//  / by zero;            System.out.println(e.toString());// 异常名称 : 异常信息。            e.printStackTrace();//异常名称,异常信息,异常出现的位置。                            //其实jvm默认的异常处理机制,就是在调用printStackTrace方法。                            //打印异常的堆栈的跟踪信息。        }               System.out.println("over");    }}

异常的由来

  问题也是现实生活中一个具体的事物,也可以通过Java的类的形式进行描述,并封装成对象,其实就是Java对不正常情况进行描述后的对象体现;

异常的处理

Java提供了特有的语句进行处理:
1.有三种常见格式:

  • 处理方式一:

    try{可能出现异常的语句;}catch(){对异常的处理语句;}
  • 处理方式二:

    try{可能出现异常的语句;}catch(){对异常的处理语句;}finally{ 一定会执行的语句;}
  • 处理方式三:

    try{可能出现异常的语句;}finally{一定会执行的语句;}
  • 注意:

    • catch是用于处理异常,如果没有catch就代表异常没有被处理过,如果该异常是检测时异常,那么必须声明;
    • finally中定义的通常是关闭资源代码,因为资源必须释放;
    • finally只有一种情况不会执行,当执行到System.exit(0);finally不会执行到;
    • 当定义自定义异常的信息时,可以使用父类已经定义好的功能,异常信息传递给父类的构造函数;
      示例代码:

      //例:class MyException extends Exception{    MyException(String message)    {        super(message);    }}

      2.对捕捉到的异常对象进行常见方法操作:
      String getMessage();//获取异常信息;

    异常处理示例:

    class Demo{int div(int a,int b)throws Exception{//在功能上通过throws的关键字声明了该功能有可能会出现问题。      return a/b;}}class  ExceptionDemo1{public static void main(String[] args){ //throws Exception    Demo d = new Demo();    try{        int x = d.div(4,0);        System.out.println("x="+x);    }catch (Exception e){        System.out.println(e.toString());    }    System.out.println("over");}}

thorws关键字

  • 在功能上通过throws的关键字声明了该功能有可能会出现问题;
  • 在函数上声明异常,便于提高安全性,让调用者进行处理,不处理编译失败;

对多异常的处理

  • 声明异常时,建议声明更为具体的异常,这样处理的可以更具体;
  • 对方声明几个异常,就对应有几个catch块,不要定义多余的catch块,如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面;
  • 建议在进行catch处理时,catch中一定要定义具体处理方式;

    代码示例:

    class Demo{int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException{//在功能上通过throws的关键字声明了该功能有可能会出现问题。    int[] arr = new int[a];    System.out.println(arr[4]);    return a/b;}}class  ExceptionDemo2{public static void main(String[] args){ //throws Exception    Demo d = new Demo();    try{        int x = d.div(5,0);        System.out.println("x="+x);    }catch(Exception e){        System.out.println("hahah:"+e.toString());    }catch (ArithmeticException e){        System.out.println(e.toString());        System.out.println("被零除了!!");    }catch (ArrayIndexOutOfBoundsException e){        System.out.println(e.toString());        System.out.println("角标越界啦!!");    }    System.out.println("over");}}

自定义异常

  项目中的特有问题并未被Java所描述并封装对象,可以按照Java对问题封装的思想,将特有的问题进行自定义的异常封装;

  1. 当在函数内部出现了throw抛出异常对象,那么就必须要给对应的处理动作,要么在内部try catch处理,要么在函数上声明(否则编译失败,RuntimeException除外);一般情况函数内部出现异常在函数上需要声明;
  2. 如何定义异常信息:因为父类中已经完成了对异常信息的操作,所以子类只要在构造时,将异常信息传递给父类,通过super语句,那么就可以直接通过getMessage方法获取自定义的异常信息;
  3. 自定义异常:必须是自定义类继承Exception或者RuntimeException;
    原因:

    • 异常体系有一个特点:异常类和异常对象都要被抛出,他们都具备可抛性,这个可抛性是Throwable这个体系的独有特点;只有这个体系中的类和对象才可以被throw和thorws操作;
    • 让类具备操作异常的共性方法;

    示例代码:

    class FuShuException extends Exception{ //getMessage();private int value;FuShuException(){    super();}FuShuException(String msg,int value){    super(msg);    this.value = value;}public int getValue(){    return value;}}class Demo{int div(int a,int b)throws FuShuException{    if(b<0)        throw new FuShuException("出现了除数是负数的情况------ / by fushu",b);//手动通过throw关键字抛出一个自定义异常对象。    return a/b;}}class  ExceptionDemo3{public static void main(String[] args) {    Demo d = new Demo();    try{        int x = d.div(4,-9);        System.out.println("x="+x);         }catch (FuShuException e){        System.out.println(e.toString());        //System.out.println("除数出现负数了");        System.out.println("错误的负数是:"+e.getValue());    }    System.out.println("over");}}

关键字throw和throws的区别:

  1. throws使用在函数上,用于抛出异常类;throw使用在函数内,用于抛出异常对象;
  2. throws后面的异常类可以跟多个,用逗号隔开,thorw后面跟的是异常对象;

示例代码:

RuntimeException:运行时异常:

Exception中有一个特殊的子类异常RuntimeException;

  1. 特点:
    • 如果在函数内抛出该异常,函数上可以不用声明,编译一样通过;
    • 如果在函数声明了该异常,调用者可以不用进行处理,编译一样通过;
  2. 原因:之所以不用在函数上声明,是因为不需要让调用者处理,但该异常发生,希望程序停止,因为运行时,出现了无法继续运算的情况,希望停止程序后,对代码进行修正;
  3. 自定义异常时:如果该异常的发生,无法再继续进行运算,就让自定义异常继承RuntimeException;
  4. 对于异常分两种:

    • 编译时被检测的异常(继承Exception);该异常在编译时,如果没有处理(没有抛也没有try),编译失败,该异常标识,代表着可以被处理。
    • 编译时不被检测的异常(RuntimeException以及其子类);运行时异常:编译时不需要处理,编译器不检查,该异常发生建议不处理,让程序停止,需要对代码进行修正;

    代码示例:

    class FuShuException extends RuntimeException{FuShuException(String msg){    super(msg);}}class Demo{int div(int a,int b)throws Exception{//throws ArithmeticException           if(b<0)        throw new Exception("出现了除数为负数了");    if(b==0)        throw new ArithmeticException("被零除啦");    return a/b;}}class ExceptionDemo4 {public static void main(String[] args) {        Demo d = new Demo();            int x = d.div(4,-9);    System.out.println("x="+x);             System.out.println("over");}}

异常在子父类覆盖中的体现

  1. 子类在覆盖父类时,如果父类的方法有抛出异常,那么子类的覆盖方法只能抛出父类的异常或者该异常的子类异常;
  2. 如果父类方法抛出多个异常,那么子类在覆盖方法是,只能抛出父类异常的子集;
  3. 如果父类或者接口的方法中没有抛出异常,那么子类在覆盖方法是,也不可以抛出异常,如果子类方法发生了异常,就必须要进行try处理,绝对不能抛;

异常的处理原则

  1. 处理方式有两种:try或者throws
  2. 调用到抛出异常的功能时,抛出几个,就处理几个,一个try对应对个catch;
  3. 多个catch,父类的catch放到最下面;
  4. catch内,需要定义针对性的处理方式,不要简单的定义printStractTrace输出语句,也不要不写,当捕获到的异常本功能处理不了时,可以继续在catch中抛出

    try{    throw new AException();}catch (AException e){    throw e;}
  5. 如果该异常处理不了,但并不属于该功能出现的异常,可以将异常转换后,在抛出和该功能相关的异常,或者异常可以处理,当需要将异常产生的和本功能相关的问题提供出去,让调用者知道,并处理,也可以将捕获异常处理后,转换新的异常;

    try{    throw new AException();}catch(AException){    //对AException处理;    thorw new BException();}
  6. 异常的应用:

    class LanPingException extends Exception{    LanPingException(String message){        super(message);    }}class MaoYanException extends Exception{    MaoYanException(String message){        super(message);    }}class NoPlanException extends Exception{    NoPlanException(String msg){        super(msg);    }}class Computer{    private int state = 3;    public void run()throws LanPingException,MaoYanException{        if(state==2)            throw new LanPingException("蓝屏了");        if(state==3)            throw new MaoYanException("冒烟了");        System.out.println("电脑运行");    }    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 (LanPingException e){            cmpt.reset();        }catch (MaoYanException e){                 test();            throw new NoPlanException("课时无法继续"+e.getMessage());             }        System.out.println("讲课");    }    public void test(){        System.out.println("练习");    }}class ExceptionTest {    public static void main(String[] args) {        Teacher t = new Teacher("毕老师");        try{            t.prelect();        }catch (NoPlanException e){            System.out.println(e.toString());            System.out.println("换老师或者放假");        }       }}
0 0
原创粉丝点击