throws子句在继承当中overrride时有什么规则?

8.throws子句在继承当中overrride时的规则  

当子类方法override父类方法时,throws子句不能引进新的checked异常。换句话说:子类override方法的throws子句checked异常不能比父类多。马克-to-win:上面一条是死语法规定,这种规定,实际上都是源于checked异常这种最初的设计。

例:1.8.1

import java.io.IOException;
class Animal{
    void call() throws IOException
    {
        System.out.println("Animal");
    }
}
class Dog extends Animal{
    void call() throws IOException
    {
        System.out.println("Dog");
    }
}

public class Test {
    public static void main(String args[]) throws IOException {
        Dog d = new Dog();
        d.call();
    }
}

为了让读者更加清楚一点,现在我们假象程序员在编Dog的时候就突发奇想想加一个SQLException,会发生什么?

例:1.8.2(有问题不能编译)

import java.io.IOException;
import java.sql.SQLException;
class Animal{
    void call() throws IOException
    {
        System.out.println("Animal");
    }
}
class Dog extends Animal{
    /*马克-to-win:这里报错说父类的throws得加上SQLException,Exception SQLException is not compatible with throws clause in Animal.call()*/     
    void call() throws IOException, SQLException
    {
        System.out.println("Dog");
    }
}

public class Test {
    public static void main(String args[]) throws IOException {
        Dog d = new Dog();
        d.call();
    }
}

更多请见:http://www.mark-to-win.com/tutorial/java_5_throwsInInheritanceOverride.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值