Lets say I have two interfaces interface A and interface B:
public interface A {
public int data();
}
public interface B {
public char data();
}
interface A has a method public int data()
and interface B has a method public char data()
.
when I implement both interfaces A and B in some class C the compiler gives me an error. Is this a flaw in java? As I presume this is one of the major reasons why we are not allowed to extend more than one class then why are we allowed to implement more than one interface when this problem still persists?
The Java Tutorials: Defining Methods - Overloading Methods states,
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists.
also,
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
The two implemented methods share a common method signature (i.e. data()
) and as such, the compiler cannot differentiate between the two and will have that single method satisfy both interface contracts.
For instance,
public class Foo implements IFoo, IBar{
public static void main(String[] args) {
Foo foo = new Foo();
((IFoo) foo).print();
((IBar) foo).print();
}
@Override
public void print() {
System.out.println("Hello, World!");
}
}
public interface IBar {
void print();
}
public interface IFoo {
void print();
}
which will output,
Hello, World!
Hello, World!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With