抽象类
- 定义:通过abstract修饰的类,就是抽象类
- 抽象类,可以拥有自己的方法,而且抽象方法必须存在于抽象类中
- 抽象类,只能靠子类实现,而不能new出来
接口
-
定义接口时,要先建一个class,然后把这个class改成interface
public interface UserService { void add(String name); void delete(String name); void update(String name); void query(String name); }
-
子类继承时,用implements,再加上接口名,不同于抽象类,它可以继承多个
public class UserServiceImpl implements UserService,TimeService//这里就是继承了两个
-
但是,子类继承之后必须重写(override),也就是写完之后,在后面按alt+enter
public class UserServiceImpl implements UserService,TimeService{ @Override public void add(String name) { } @Override public void delete(String name) { } @Override public void update(String name) { } @Override public void query(String name) { } @Override public void timer() { } }
内部类
- 一个Java类中,可以有多个class类,但是只能有一个public class
异常Exception
-
第一个比较严重的异常(错误),定义两个方法(a(),b()),其中,a方法调用b方法,b方法调用a方法,这个样将他们所存在的类给new出来
public class Demo01 { public static void main(String[] args) { new Demo01().a(); } public void a(){ b(); } public void b(){ a(); } }
-
抛出异常,捕获异常
异常处理五个关键字:try, catch, finally, throw, throws -
异常的举例
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("Exception"); }catch(Throwable e){ System.out.println("Throwable"); } finally{ System.out.println("finally"); } } }
1)上述的代码中,try是监控区域,监控大括号内的这句话有没有异常
2)catch中的括号是所要捕获的异常类型,其中(throwable是最大的,其次是error和exception),其中exception后面的e,是我们假设这个异常叫做e,还可以进行多个catch
3)最后的finally是处理善后工作,无论如何都会执行
4)快捷键Ctrl + Alt + Tpublic class Test2 { public static void main(String[] args) { int a = 1; int b = 0; try { System.out.println(a/b); } catch (Exception e) { e.printStackTrace(); } finally { } } }
其中,e.printStackTrace( ); 是打印错误的栈信息
5)自己也可以在catch中主动结束,System.exit( 0 );
6)throw 和 throws的区别public class Test { public static void main(String[] args) { new Test().decide(1,0); } public int decide(int a, int b) throws ArithmeticException{ if (b == 0){ throw new ArithmeticException(); }else { System.out.println(a/b); } } }
throw是在方法里面,主动抛出异常
throws假设在方法中(throw)处理不了这个一场,则会在方法上抛出这个异常(见上方的代码)
7)try 和 catch 这个异常处理机制,使得如果程序遇到异常之后,不会停止,而是继续向下执行 -
自定义异常