Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    ...
}
like image 439
Dänu Avatar asked Jan 19 '12 14:01

Dänu


2 Answers

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.

like image 119
Mchl Avatar answered Nov 10 '22 09:11

Mchl


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
like image 22
Sandro Munda Avatar answered Nov 10 '22 10:11

Sandro Munda