Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Super and sub interfaces both in a class(class A implements SuperInterface, SubInterface)

Tags:

java

interface

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)?

like image 990
c.P.u1 Avatar asked Jan 23 '13 16:01

c.P.u1


3 Answers

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

like image 184
NPE Avatar answered Oct 19 '22 07:10

NPE


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.

like image 2
Ted Hopp Avatar answered Oct 19 '22 08:10

Ted Hopp


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)

like image 2
SLaks Avatar answered Oct 19 '22 09:10

SLaks