首页 > 编程 > Java > 正文

Java 继承接口同名函数问题

2019-11-08 02:32:04
字体:
来源:转载
供稿:网友

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便已经无法编译。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表