我有两个 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 classTuna
has a name, signature, and return type that matches the method declared in interfaceFish
and also matches the method declared in interfacePiano
; it is considered to implement both.
文本接着指出,如果方法签名具有不同的返回类型,例如 double
和 int
,则无法在将产生相同的类和编译时错误。
关于java - 在 Java 类中实现的具有相同方法签名的两个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9863835/