问题描述
我有两个 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.
正文接着指出,如果方法签名具有不同的返回类型,例如 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 类中实现的具有相同方法签名的两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!