Java 继承接口同名函数问题

来源:互联网 发布:win10多核优化怎么开 编辑:程序博客网 时间:2024/05/14 21:36

在Java中如果一个类同时继承接口A与B,并且这两个接口中具有同名方法,会怎么样?


动手做实验:

interface A{    void fun();}interface B{    void fun();}interface C extends A,B{}public class Test implements C{    @Override    public void fun() {        System.out.println("hehe");    }    public static void main(String[] args) {        new Test().fun();    }}
运行截图:


上例的情况,可以正常编译运行,输出"hehe",因为A与B中的fun具有相同的签名(参数个数与类型相同)

interface A{    void fun();}interface B{    int fun(int x);}interface C extends A,B{}public class Test implements C{    @Override    public void fun() {        System.out.println("hehe1");    }    @Override    public int fun(int x) {        return 0;    }    public static void main(String[] args) {        new Test().fun();    }}



上例也是可以编译运行的,因为A与B中的fun方法具有不同的函数签名,本质上是两个方法,分别实现即可。


interface A{    void fun();}interface B{    int fun();}interface C extends A,B{}public class Test implements C{    @Override    public void fun() {        System.out.println("hehe");    }    public static void main(String[] args) {        new Test().fun();    }}


而这种具有相同函数签名,但不同返回值的方法,是没有办法编译的,接口C便已经无法编译。

0 0
原创粉丝点击