在Java类中实现的具有相同方法签名的两个接口 [英] Two interfaces with same method signature implemented in Java class

查看:303
本文介绍了在Java类中实现的具有相同方法签名的两个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Java接口和一个实现类。

I have two Java interfaces and one implementing class.

(我使用Eclipse直接运行程序,我没有尝试检查任何编译器警告cetera通过从命令行显式编译。)

(I have used Eclipse to run the program directly, and I did not try to check any compiler warning et cetera by explicitly compiling from the command line.)

为什么它们运行没有问题?为什么Java允许这样做,即使它满足两个接口的合同,但在实现类中产生歧义?

Why do they run without problem? Why does Java allow this, even when it satisfies the "contract" of both interfaces but create ambiguity in implementing class?

更新了示例。

public interface CassettePlayer {
    void play();
}

public interface DVDPlayer {
    void play();
}

public class CarPlayer implements CassettePlayer,DVDPlayer{

    @Override
    public void play() {
        System.out.println("This plays DVD, screw you Cassette !");
    }

    public static void main(String args[]) {
        CarPlayer cp = new CarPlayer();
        cp.play();

        CassettePlayer firstInterface = new CarPlayer();
        firstInterface.play();

        DVDPlayer secondInterface = new CarPlayer();
        secondInterface.play();
    }
}


推荐答案

Java语言规范第8.1节中明确允许的情况。 5


一个类中的单个方法声明允许实现多个超级接口的方法。例如,在代码中:

It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code:

interface Fish { int getNumberOfScales(); }
interface Piano { int getNumberOfScales(); }
class Tuna implements Fish, Piano {
   // You can tune a piano, but can you tuna fish?
   int getNumberOfScales() { return 91; }
}

方法getNumberOfScales在类Tuna中有一个名称,签名和返回类型它与在Fish接口中声明的方法匹配,并且匹配在接口Piano中声明的方法;它被认为实现两者。

the method getNumberOfScales in class Tuna has a name, signature, and return type that matches the method declared in interface Fish and also matches the method declared in interface Piano; it is considered to implement both.

然后文本继续注意,如果方法签名有不同的返回类型, code> double 和 int ,将无法在同一个类中实现两个接口,并且会产生编译时错误。

The text then goes on to note that if the method signatures had different return types, such as double and int, there would be no way to implement both interfaces in the same class and a compile time error would be produced.

这篇关于在Java类中实现的具有相同方法签名的两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆