Why Interface in Case 1 throws compile time error but in Case 2 compiles successfully

Ankit Srivastava :

I am having two interfaces in "CASE 1" in which I have same method with different return types and I am extending both the interfaces in another interface then I am getting compile time error as return types are incompatible for inherited methods but here when we are extending two interfaces in third interface then methods are getting overloaded and in method overloading return type of method has no effect then why is this giving error.

Also if I am same methods in two interfaces with same return types in "CASE 2" and extending both the interfaces in third interface then here I am not getting any errors. Why?

CASE 1

Interface1.java

public interface I1
{
int m();
}

Interface2.java

public interface I2
{
void m();
}

Interface3.java

public interface I3 extends I1,I2
{

}

CASE 2

Interface1.java

public interface I1
{
int m();
}

Interface2.java

public interface I2
{
int m();
}

Interface3.java

public interface I3 extends I1,I2
{

}
Jon Skeet :

In your first case, the interface is inconsistent. It would be impossible for any class to implement it, as it can't satisfy the constraints of "there must be an int m() method" and "there must be a void m() method".

You say "in method overloading return type of method has no effect" - that's not quite true. In method overloading, the return type isn't part of the signature. You can't overload methods by changing just the return type, precisely because they have the same signature:

class Foo
{
    public void m() {}
    public int m() { return 1; }
}

Result:

error: method m() is already defined in class Foo

In your second case, the interface is consistent. It's entirely possible to implement it, just with a single method int m() { ... }. The fact that the single method would be used to implement both I1.m and I2.m is not a problem.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113534&siteId=1