我在这里有点进退两难,
说我有课
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
为什么会这样?
最佳答案
每次你实现一个接口(interface)(或者从父类覆盖一个方法,同样的事情),你需要尊重那个接口(interface)的契约。遵守约定意味着您不能抛出比接口(interface)声明中更多的异常。
在这两种情况下,Interface
是契约(Contract),Parent
是实现(通过类 Child
中发生的两者之间的“绑定(bind)”)。
在第一种情况下,界面显示methodOne()
允许抛出异常,但不是必须的。您在 Parent
中的实际实现不会抛出任何东西,所以它是合约的一个子集并且没问题。
在第二种情况下,界面显示methodOne()
不会抛出任何东西(*),因此任何实现都不允许抛出任何异常。但是,Parent
中的实现要求允许抛出,这与接口(interface)契约不兼容;因此编译器错误。
另请注意,在第二种情况下,您可以很好地覆盖 methodOne()
在Child
空的 throws
声明,以便签名符合接口(interface)协定。然后您可以调用 super.methodOne()
并重新包装 Exception
作为RuntimeException
(例如)。
顺便说一句:
- 如果您实现多个具有相同方法签名的接口(interface),则该实现只能抛出
throws
的交集。所有接口(interface)的声明; - 你不需要使用
abstract
接口(interface)中的关键字,因为接口(interface)中的方法声明本质上总是抽象的。
(*) 当然 RuntimeException 除外。
关于java - 实现在接口(interface)和父类中声明的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33267862/