Dänu
Dänu

Reputation: 5929

Superclass and subclass each with it's own interface

Is the following ok? (keep in mind that I didn't write the bodies of the classes and I also didn't write the interfaces ;-))

abstract class SuperClass implements SuperInterface

class SubClass extends SuperClass implements SubInterface

Or is this generally considered bad practice?

What made me wonder is, that the following didn't work:

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

Upvotes: 7

Views: 2296

Answers (3)

Mchl
Mchl

Reputation: 62369

It's neither good nor bad. SubClass here implements both SuperInterface and SubInterface (as well as interface defined by SuperClass' public methods). If that's what you need - that's fine.

As for your second example

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

You declared the list of SubInterface elements, but want to fetch SuperInterface elements from it. If SubInterface extends SuperInterface then this has some sense. Otherwise not.

Upvotes: 10

Sandro Munda
Sandro Munda

Reputation: 41030

It is correct. Why not ?

Your SuperClass implements a SuperInterface which also implemented by your SubClass (thanks to the the SubClass extends SuperClass).

In addition, your SubClass implements another interface (SubInterface).

There is nothing wrong in your code/architecture.

SuperClass -- implements --> SuperInterface
SubClass -- extends --> SuperClass -- implements --> SuperInterface*, SubInterface
  • Implicit implements due to the extends of SuperClass

Upvotes: 3

Aviram Segal
Aviram Segal

Reputation: 11120

this is fine depending on what you want to achieve (there might be a better design for what you are trying to do), keep in mind that SubClass is both SuperInterface and SubInterface

Upvotes: 1

Related Questions