Search code examples
javacompiler-constructioninterfacemultiple-inheritance

Two interfaces with same method signature implemented in Java class


I have two Java interfaces and one implementing class.

(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.)

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?

Updated the example.

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

Solution

  • This scenario specifically allowed in the 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.

    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.