Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing multiple interfaces with same method signatures

Tags:

java

interface

Given to interfaces I1 and I2

interface I1{int i=1; void foo();}

interface I2{int i=2; int foo();}

is there any way for a class A to implements both of them? I can't manage to correctly implement the foo methods, and this makes sense, because having the same input parameters in I1.foo() and I2.foo() wouldn't let class A distinguish between the two.

But the constant "i" is not a problem, provided that you cast A to one of the interfaces when trying to read them:

System.out.println(((I2)new A()).i);

it looks like the compiler says: "Ok i'm leaving you with an ambiguity in 'potentiality', but when it comes to 'actuality' i'm going to stop you". And the "actuality" for the methods seems to come earlier.

Am I right? Am I missing something? Am i just going crazy imagining a compiler talking to me like an aristotelian?

like image 848
Luigi Cortese Avatar asked Feb 14 '23 23:02

Luigi Cortese


1 Answers

No. You can think of interfaces in Java as contracts. Because these interfaces have the same method name (but different return types) no one class can fulfil both contracts. If they had different arguments the answer would be yes.

like image 129
Elliott Frisch Avatar answered Mar 16 '23 12:03

Elliott Frisch