Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two interface have same method name with different return type

Tags:

java

oop

This question is for understanding interfaces in Java. Here is a very simple example of implementing a interfaces in Java.

interface ParentA {
    void display();
}

interface ParentB {
    int display();
}

class Child implements ParentA, ParentB {
    @Override
    public void display() {
        System.err.println("Child ParentA");
    }
    //ERROR : The return type is incompatible with ParentB.display()

    //So added method with int return type too
    @Override
    public int display() {
        System.err.println("Child ParentB");
    }
}

This case can happen in large Java application where two interface can have method with same name. I thought that since return type is different JVM will know which interface's method we are overriding.

What is the best explanation for this? Does this situation make sense?

Thanks in Advance

like image 1000
IfOnly Avatar asked Oct 21 '25 08:10

IfOnly


2 Answers

If you found yourself in this situation and couldn't solve in a cleaner way, you could have one or two inner classes that forward the calls to newly named methods:

class Child {
    private class ParentAImp implements ParentA {
      @Override
      public void display() {
          displayParentA();
      }
    }

    private class ParentBImp implements ParentB {
      @Override
      public int display() {
          return displayParentB(); 
      }
    }

    public ParentA asParentA(){ return new ParentAImp(); }
    public ParentB asParentB(){ return new ParentBImp(); }

    private void displayParentA() {
        System.err.println("Child ParentA");
    }

    private int displayParentB() {
        System.err.println("Child ParentB");
        return 0;
    }
}

Drawback is now to get from Child to interface you have to do:

ParentA parentA = child.asParentA();
ParentB parentB = child.asParentB();
like image 82
weston Avatar answered Oct 23 '25 00:10

weston


Because method with same signature is not allowed, It confuses compiler to detect the exact override-equivalent method from the declared once.

JLS (§8.4.2)

Two methods or constructors, M and N, have the same signature if they have,

  • the same name
  • the same type parameters (if any) (§8.4.4), and
  • after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

It is a compile-time error to declare two methods with override-equivalent signatures in a class.

like image 45
akash Avatar answered Oct 23 '25 00:10

akash