【发布时间】:2015-10-21 19:42:14
【问题描述】:
我这里有点两难,
说我有课
public class Child extends Parent implements Interface{
public static void main(String[] args){
Child child = new Child();
child.methodOne(); } }
在哪里
abstract class Parent {
public void methodOne() {
System.out.print("cannot fly ");
}}
interface Interface {
public abstract void methodOne() throws Exception;}
这个结构没有编译错误
如果我这样做了
abstract class Parent {
public void methodOne() throws Exception {
System.out.print("cannot fly ");
}}
interface Interface {
public abstract void methodOne(); }
两个编译错误上升说
Exception Exception in throws clause of Parent.methodOne() is not compatible with Interface.methodOne()
和
Unhandled exception type Exception
要求在main 方法中添加throws 或try/catch
为什么会这样?
【问题讨论】:
-
如果在两个地方都添加 throws 子句会发生什么?
-
我认为对发生的事情有很多解释。总之,您从
Parent继承了一个部分匹配Interface签名的方法。要解决这个问题,只需覆盖该方法并使其不引发检查异常。例如try { super.methodOne(); } catch (Exception e) { throw new RuntimeException(e); }
标签: java inheritance