JAVA之抽象·接口·异常

119 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

抽象:

1.不能new抽象类,只能靠子类去实现

2.抽象类中可以写普通的方法

3.抽象方法必须在抽象类中

abstract,抽象方法,只有方法名字,没有方法的实现

很好理解就不细讲了

接口:

interface

普通类:只有具体实现

抽象类:具体实现和规范(抽象方法)都有

接口:只有规范,自己无法写方法·专业的约束,接口的本质是契约

利用接口实现多继承

接口定义方法都是抽象的public abstract 简写为void 方法()

定义的常量都是public static final

#service
package OOP.demo2;
public interface service {
    void add(String name);
    void delete(String name);
    void updata(String name);
    void query(String name);
}
#serviceIMpl
package OOP.demo2;
public class serviceIMpl implements service{


    @Override
    public void add(String name) {
    }
    @Override
    public void delete(String name) {
    }
    @Override
    public void updata(String name) {
    }
    @Override
    public void query(String name) {
    }
}

异常:

Exception:实际中出现的各种非预期

检查性异常、运行时异常、错误(不是异常)

异常处理机制:

抛出异常/捕获异常

五个关键字:try.catch.finally.throw.throws

tips:try,catch快捷键:想要捕获某个异常ctrl+alt+t

例子,简单的处理

package OOP.demo3;
public class test {
    public static void main(String[] args) {
        int a= 1;
        int b = 0;
        try {
            System.out.println(a/b);  //监控
        } catch (Exception e) {//捕获
            System.out.println("异常");  //操作
        } finally {
            System.out.println("xino");//善后
        }
    }
}

小结:可以设置捕获多个异常,但必须把最大的异常写在最下面

throw/throws

抛出异常常用于方法中

throw

package OOP.demo3;
public class test {
    public static void main(String[] args) {
new test().test1(1,0);
    }
    //假设这个方法处理不了这个异常,就抛出异常
    public void test1(int a,int b) {
        if(b==0){
            throw new ArithmeticException();
        }
        System.out.println(a/b);
    }
}

throws

package OOP.demo3;
public class test {
    public static void main(String[] args) {
        try {
            new test().test1(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
    public void test1(int a,int b) throws ArithmeticException {
        if(b==0){
            throw new ArithmeticException();
        }
        System.out.println(a/b);
    }
}

throw与throws的比较

****1、throws出现在方法函数头;而throw出现在函数体。

2、throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象。

3、两者都是消极处理异常的方式(这里的消极并不是说这种方式不好),只是抛出或者可能抛出异常,但是不会由函数去处理异常,真正的处理异常由函数的上层调用处理。

自定义异常

须继承exception

class WrongInputException extends Exception { 
// 自定义的类 WrongInputException(String s) { super(s); } } 
class Input 
{ void method() throws WrongInputException {
 throw new WrongInputException("Wrong input"); // 抛出自定义的类 } }
  class TestInput {
   public static void main(String[] args){
    try { new Input().method(); }
     catch(WrongInputException wie) {
      System.out.println(wie.getMessage()); } } }