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

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

问题描述

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

I have two Java interfaces and one implementing class.

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

(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; }
}

Tuna 类中的方法 getNumberOfScales 具有与接口 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.

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

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天全站免登陆