【发布时间】:2014-07-03 13:42:38
【问题描述】:
考虑以下代码:
public interface I1 {
public void bar1() throws IOException;
}
public interface I2 extends I1 {
public void bar2() throws Exception;
}
public interface I3 {
public void bar3() throws Exception;
}
public abstract class A implements I2 {
public void bar2() throws Exception{};
public void bar3() throws Exception{};
protected abstract void bar4();
protected void bar5() {};
}
现在,我创建了一个类,B,如下所示:
public class B extends A implements I3 {
@Override
protected void bar4() {}
public void bar1() {}
}
为什么编译器让我这样做?我的意思是,不应该是:public void bar1() throws IOException;
【问题讨论】:
-
你可以这样想:I1 告诉我们可能发生的最坏情况是什么,因为每个人都接受一个实现 I1 的类需要为最坏的情况做好准备。现在你实现了
bar1(),但它实际上并没有抛出IOException。可能发生的最坏情况是什么?与抛出IOException相比,该实现显然没有那么糟糕。如果其他一些类使用实现I1 的类,它不会改变任何东西。该实现已准备好处理IOExceptions,但它们永远不会发生。
标签: java oop exception inheritance interface