c.P.u1
c.P.u1

Reputation: 17094

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

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

Upvotes: 17

Views: 5056

Answers (5)

jaco0646
jaco0646

Reputation: 17066

Redundant inheritance declarations have an effect on certain reflection calls.

interface One {}
interface Two extends One {}
static class Three implements Two {}
static class Four implements One, Two {}

public static void main(String... args) {
    Three three = new Three();
    Four four = new Four();
    System.out.println(Arrays.toString(three.getClass().getInterfaces()));  // [Two]
    System.out.println(Arrays.toString(four.getClass().getInterfaces()));  // [One, Two]
}

This probably isn't a reason to design your classes in a certain way, but demonstrates that it does have an effect at runtime.

Upvotes: 0

SLaks
SLaks

Reputation: 887365

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)

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 2

MrSmith42
MrSmith42

Reputation: 10151

1) Why not implementing A twice is redundant but leads to no confusion.

2) interface B may be changed (and may no longer extending A). AClasswould still implement A and B

Upvotes: 1

NPE
NPE

Reputation: 500267

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

Upvotes: 6

Related Questions