2

there is two interfaces A and B:

public interface A {
}

public interface B extends A{
}

A and B have one subclass each:

public abstract class ABase implements A{
}

public abstract class BBase implements B{
} 

and now I want make BBase extends ABase, like this:

public abstract class BBase extends ABase implements B{
}

But I think this is a bad design, because ABase and B are both subclass of A:

A <----------- B
|              |
|              |
ABase <----- BBase
2
  • 1
    Does this compile? Jul 22 at 0:34
  • 1
    Neither ABase nor B subclass A
    – Caleth
    Jul 22 at 10:07
7

That's very common, for example in java.util (in puml format)

@startuml

title Classes - Class Diagram

interface Collection
interface List extends Collection
class AbstractCollection implements Collection
class AbstractList extends AbstractCollection implements List


@enduml

plantuml image

2

There's nothing wrong with it.

Interface B is an extension of A, typically meaning that it requires a few additional methods to be implemented.

If class BBase extends ABase (and you're sure that this is a good design decision, as nowadays we often prefer composition over inheritance), then if BBase matches the semantics of interface B and technnically fulfills its requirements, it should declare that it implements B.

2

A couple of things to add to the existing answers. Caleth's comment is correct that classes do not 'subclass' interfaces. They 'implement' them. The distinction is that interfaces declare what methods a class must have on it. As long as your interfaces don't have conflicting ideas about what the same method signature means, you can implement as many as you like in a class. The fact that B extends A strongly implies that B will agree with A on the meaning of each method A declares making such disagreements unlikely.

There's one thing to be mindful of here. though: in the ancient past, interfaces in Java could not contain code of any sort, only declarations. Java now has support for default methods with implementations. Implementing multiple interfaces, especially related ones, could give rise to the situation where you have different default implementations for the same method from the implemented interfaces. The rules around how this is resolved are clearly defined and consistent (to my knowledge) but not necessarily obvious or well-known. Using default methods in this kind of situation might create some confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.