抽象类和接口

上午主要讲了抽象类和接口

抽象类特点:抽象类不能直接实例化,但可以声明出对象的引用以指向非抽象子类的对象(格式统一方便编程)
除非子类采用具体方法替代抽象类中的全部抽象方法,否则子类本身也被自动认为是抽象的,此时必须手动在子类上加上abstract关键字。

异常中的关键字
1.throw 在方法内部,抛出异常对象
2.throw 后面必须写new 对象,对象必须是异常的对象
方法中声明关键字
throws 在方法的声明声明上,表明此方法可能出现异常
请调用者处理
throws 后面必须写异常的类名
调用了一个抛出异常方法调用者就必须处理
不处理编译失败

public class ExceptionDemo {
public static void main(String args[]) throws Exception{

     int[] arr = null;
     int i = getArray(arr);
     System.out.println(i);

}
public static int getArray(int[] arr) throws Exception
{
//判断方法参数的合法性
if(arr==null)
{
//抛出异常的形式
//关键字throw
throw new Exception(“传递数组不存在”);
}
//判断数组是不是有元素
if(arr.length==0)
{
throw new Exception(“数组中没有任何元素”);
}
int i = arr[arr.length-1];
return i*2;
}
}
异常处理方式:
try..catch..finally
格式
try{
被检测的代码
可能出现异常的代码
}catch(异常类名变量){
异常的处理
}finally{
必须要实行的代码
}

public class ExceptionDemo1 {
public static void main(String args[])
{
int[] arr = new int[0]; //throw new NullPointerException(“数组不存在”);
try{ //try 检测到了有异常发生,捕获到一个异常对象,将异常抛给catch代码块处理这个异常

       int i = getArray(arr);
       System.out.println(i);

   }catch(NullPointerException ex) {    //throw new NullPointerException("数组不存在");
       System.out.println(ex);         //NullPointerException ex = new NullPointerException("数组不存在");
   }catch(ArrayIndexOutOfBoundsException ex){
       System.out.println(ex);
   }
   finally{
       System.out.println("Gome over");
   }

}

接口与抽象类的不同:
接口只抽象行为,而抽象类则要指定属性、具体的方法和抽象的方法。
工程中,接口用的比抽象类更多一些
抽象类只能单继承,而接口可以多实现!但是,当将继承(或实现)的子类有默认方法实现时,必须用抽象类(毕竟是个class,功能多一些)

接口和抽象类区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值