Superclass and subclass, each with its own interface

Is the following normal? (keep in mind that I did not write the body of the classes, and I also did not write the interfaces ;-))

abstract class SuperClass implements SuperInterface class SubClass extends SuperClass implements SubInterface 

Or is this usually considered bad practice?

Which made me think that the following did not work:

 List<SubInterface> myList; ... for(SuperInterface si : myList) { ... } 
+7
source share
3 answers

This is neither good nor bad. SubClass here implements both SuperInterface and SubInterface (as well as an interface defined by public methods of SuperClass ). If this is what you need, that’s fine.

Regarding your second example

 List<SubInterface> myList; ... for(SuperInterface si : myList) { ... } 

You have declared a list of SubInterface elements, but want to extract SuperInterface elements from it. If the SubInterface continues with SuperInterface , then this makes some sense. Otherwise, no.

+10
source

It is right. Why not?

Your SuperClass implements SuperInterface, which is also implemented by your SubClass (due to the fact that SubClass extends SuperClass).

In addition, your SubClass implements a different interface (SubInterface).

There is nothing wrong with code / architecture.

 SuperClass -- implements --> SuperInterface SubClass -- extends --> SuperClass -- implements --> SuperInterface*, SubInterface 
  • Implicit implementations due to SuperClass extensions
+3
source

this is normal depending on what you want to achieve (maybe the best design for what you are trying to do), keep in mind that SubClass is SuperInterface and SubInterface

+1
source

All Articles