如果类A在扩展类B的同时又实现了接口C,且B与C有相同方法event,但各自抛出不同的异常,那么接口的event()方法就不能改变在基类中的event()方法的异常接口。否则的话,使用基类的时候就不能判断是否捕获了正确的异常。这段话怎么理解?
接口:Storm .基类:Inning 以及子类 StormInning,如下,对于StormInning的event方法,抛出RainedOut和BaseException都会报错。
interface Storm{
public void event() throws RainedOut;
}
class Inning{
public void event() throws BaseException;
}
class StormInning extends Inning implements RainedOut{
public void event() /*throws RainedOut*/{
}
}
接口:Storm .基类:Inning 以及子类 StormInning,如下,对于StormInning的event方法,抛出RainedOut和BaseException都会报错。
interface Storm{
public void event() throws RainedOut;
}
class Inning{
public void event() throws BaseException;
}
class StormInning extends Inning implements RainedOut{
public void event() /*throws RainedOut*/{
}
}
接口中定义的异常就是个摆设,实际生效的是你具体实现类中声明的异常。
接口中定义的异常对其实现类具有约束作用,使其不能超过自己的范围(比如接口NullPointerException,实现类Exception就会报错),或者干脆不定义异常也是可以的。