Two interfaces with same method signature implemented in Java class(在 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.
正文接着指出,如果方法签名具有不同的返回类型,例如 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 类中实现的具有相同方法签名的两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 类中实现的具有相同方法签名的两个接口
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01