复习abstract和异常

面向对象 oop

抽象类

abstract class Shape{//定义抽象类Shape
    protected String color;//定义保护型字符color
    void setter(String c){color=c;}//创建构造器方法
    String getter(){return color;}//构造访问器方法
    abstract  double getArea();//定义抽象面积
}
class Circle extends Shape{//创建Shape子类Circle
    double radius=0;//定义double型圆的半径radius
    Circle(String c,double r){color=c;radius=r;}//类的带参数构造方法
    double getArea(){return radius*radius*Math.PI;}//求圆的面积,返回其值
}
class Rectangle extends Shape{
    //创建子类Rectangle
    double length,width=0;
    Rectangle(String c,double l,double w){color=c;length=l;width=w;}//构造带参数函数
    double getArea(){return length*width;}//返回长方形的体积
}
public class Test{
    //构造主类
    public static void main(String[] args){
        //构造主函数
        Shape[] shapes={new Circle("蓝色",1.0),new Rectangle("红色",2.0,3.0)};//给各变量赋值
        displayInfo(shapes);//显示为何种图形的面积
    }
    public static void displayInfo(Shape[] shapes){
        //构造方法遍历数组中每个图形对象,并显示图形的相关信息,包括图形颜色和面积
        for(Shape shape:shapes){
            //for循环遍历数组中每个图形对象
            System.out.println(shape.getter()+shape+"面积为"+shape.getArea());
            //显示带颜色形状图形面积大小
        }
    }
}

接口类

1.约束
2.定义一些方法,让不同的人实现
3.public abstract
4.public static final
5.接口不能被实例化,接口没有构造方法
6.implements可以实现多个接口
7,必须要重写接口中的方法

内部类outer inner

在内里面,调用

异常

抛出异常 try的内容

捕获异常catch

1.System.out.println(a/b);

catch(ArithmeticException e)

public void a(){
    b();
}
public void b(){
    a();
}

new Demo01().a();

catch(Throwable e)

try{
    //System.out.println(a/b);
    new  Demo01().a();
}catch(Throwable e){
    System.out.println("程序出现异常");
}finally{
    System.out.println("finally");
}

finally最终都会执行

应对不同种类异常的类型
try{
    //System.out.println(a/b);
    new  Demo01().a();
}
catch(Error e){
    System.out.println("Error");
}
catch(Exception e){
    System.out.println("Exception");
}
catch(Throwable e){
    System.out.println("Throwable");
}
finally{
    System.out.println("finally");
}

方法里写异常

方法名 + throws exception

自定义异常

MyException

try-catch-finally实际应用中的经验总结

  1. 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
  2. 在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
  3. 对于不确定的代码,也可以加上try-catch,来处理潜在的异常Ctrl + Alt +T
  4. 尽量去处理异常,切记只是简单的调用printStackTrace()去打印输出
  5. 具体如何处理异常,要根据不同的业务需求和异常类型去决定
  6. 尽量添加finally语句块去释放占用的资源
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值