java - 在 Java 类中实现的具有相同方法签名的两个接口(interface)

标签 java compiler-construction interface multiple-inheritance

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

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

为什么他们运行没有问题?为什么 Java 允许这样做,即使它满足两个接口(interface)的“契约”但在实现类时产生歧义?

更新了示例。

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 Language Specification, section 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; }
}

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.

文本接着指出,如果方法签名具有不同的返回类型,例如 doubleint,则无法在将产生相同的类和编译时错误。

关于java - 在 Java 类中实现的具有相同方法签名的两个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9863835/

相关文章:

java - 在java中强制警告

java - Hibernate:仅从一张表中选择所有内容,而不是从 3 个连接表中选择所有内容

java - 尝试从 Java 连接到 Amazon S3 时出现 "Invalid argument GET '/'",有什么想法吗?

java - 如何让 Talend 进程正确捕获 SIGINT?

php - 用 PHP 编写编译器

c - 为什么结构的大小不等于其各个成员类型的大小之和?

oop - 如何处理 "optional interfaces"?

interface - 即使我只有一个实现,我还应该对接口(interface)进行编码吗?

arrays - 如何使用 typescript 的字符串索引接口(interface)?

java - 如果我散列 IV 值,是否有任何安全改进?