Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inheriting from several Interfaces having same method signature

1) How to solve this problem in Java?

2) What if only the return types are different in the interfaces?

like image 232
jai Avatar asked Dec 21 '22 13:12

jai


2 Answers

1) How to solve this problem in Java?

Essentially, the different "versions" of the method in the respective interfaces all bind to the same implementation method.

  • If that's what you want, fine.

  • If you actually want a different version of the method for each interface then you are stuck. You can't do that in Java.


2) What if only the return types are different in the interfaces?

If the return types are incompatible, you cannot write a class that implements all of the interfaces. Compilation error.

So when are return types compatible?

  • Prior to Java 5.0, the return type of an overriding or implementing method had to be the same as the return of the overridden or implemented method.

  • In Java 5.0, the language was modified to allow you to override / implement a method with a return type that is a subclass of the return type of the overridden / implemented method.

So ... if you are using Java 5.0 or later ... you need to implement using a return type that is the same type or a subclass of all of the return types of all versions of the method. If there is no such type, then the class is not implementable. And obviously, this doesn't work for primitive return types, because no subclass relationship exists between primitive types.

(Note: in Java 5.0 +, we are talking about a subclass relationship between the declared return types ... not the runtime types of the returned objects.)

like image 194
Stephen C Avatar answered May 14 '23 12:05

Stephen C


1) This is not a real problem as an interface does not define an implementation. In the example all three cases are going to call the same implementation.

2) There is no problem if return types are compatible (see covariant return types).Simply, you can change the return type if the new one is extending the one defined in the interface:

class A {
 ...
 List returnList();
}

class B extends A {
 ...
 ArrayList returnList(); // possible as an ArrayList is a List
}
like image 26
ic3 Avatar answered May 14 '23 12:05

ic3