interface A {
public void doSomething();
}
interface B extends A {
public void doSomethingElse();
}
public class AClass implements A, B {
public void doSomething() {}
public void doSomethingElse() {}
}
Why does Java permit such a declaration? What's the use of implementing both interfaces when same thing can be achieved by implementing the SubInterface (B)?
I think the "why" question can only be answered by Java designers.
One reason might be that it permits retrofitting extends A
to B
without breaking any existing classes that already happen to implement both.
Another reason for using this construct might be to make it immediately clear to the end user of AClass
that the class implements both A
and B
. This is discussed in Redundant implementation of List interface in ArrayList.java
This is simply a convenience. It can be difficult to track what the interface structure is, and would be onerous on a programmer to have to track it all down. Besides, no good can come from not permitting redundant interfaces: implementing an interface multiple times may be unavoidable. For example:
interface A { ... }
interface B extends A { ... }
interface C extends A { ... }
public class AClass implements B, C { ... }
In this case, A is "implemented" twice, but that's no problem. It simply means that AClass
must implement each method declared in A
, B
, and C
.
Had this been an error, adding a base interface to an existing public interface would have been a breaking change.
(in case client code has a class that already implements both interfaces)
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