面向对象 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实际应用中的经验总结
- 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch,来处理潜在的异常Ctrl + Alt +T
- 尽量去处理异常,切记只是简单的调用printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加finally语句块去释放占用的资源